React Native数组指定位置插入元素的实现方法及语法疑问求助
Hey there! Let's break down your problem step by step and fix your code properly.
First, let's spot the issue in your current code
When you use ...mydata[i] to spread a single object into your tmpdata array, you're actually splitting the object's key-value pairs into individual array elements. For example, {name: 'Mickey', color: 'Blue'} gets turned into ['Mickey', 'Blue']—this messes up the structure of your array, mixing strings and objects instead of keeping all elements as objects like you intended.
Correct ways to insert elements at a specific position
Here are two reliable approaches to achieve what you want:
1. Use the splice method (modifies the original array)
JavaScript arrays have a built-in splice method designed exactly for adding/removing elements at specific positions. The syntax is array.splice(startIndex, deleteCount, itemToAdd).
To insert your new item at index 1 (between Mickey and Donald):
let mydata = [ { name: 'Mickey', color: 'Blue'}, { name:'Donald' , color: 'Yellow'}, { name: 'Goofy', color : 'Red'}]; const newItem = { name:'Daisy', color:'Pink' }; // Insert newItem at index 1, delete 0 existing elements mydata.splice(1, 0, newItem); console.log(mydata[1].name); // Outputs "Daisy"
If you don't want to modify the original array, make a shallow copy first:
const newMydata = [...mydata]; newMydata.splice(1, 0, newItem);
2. Use spread operator to create a new array (immutable approach)
If you prefer functional programming and want to avoid modifying the original array, split the array into three parts and recombine them:
let mydata = [ { name: 'Mickey', color: 'Blue'}, { name:'Donald' , color: 'Yellow'}, { name: 'Goofy', color : 'Red'}]; const newItem = { name:'Daisy', color:'Pink' }; const newMydata = [ ...mydata.slice(0, 1), // Elements before index 1 newItem, // The new element to insert ...mydata.slice(1) // Elements from index 1 onwards ]; console.log(newMydata[1].name); // Outputs "Daisy"
Can you directly use mydata[i] for this?
Great question! In JavaScript, you can assign values directly to mydata[i], but this replaces the element at that index instead of inserting a new one. For example:
mydata[1] = newItem; // Replaces Donald with Daisy, array length stays 3
This is different from inserting, which shifts all elements after the target index to the right and increases the array length. So direct assignment works for replacement, but not insertion.
Compared to .NET: JavaScript arrays are dynamic (like .NET's List<T>) rather than fixed-length arrays. The splice method here is equivalent to List.Insert() in .NET for inserting elements.
内容的提问来源于stack exchange,提问作者Jsmidt

