在特定索引处将JS插入数组

25
我想在特定索引处将字符串插入到数组中。 我该怎么做?
我尝试使用push()。
1个回答

36

很简单。假设您有一个包含5个对象的数组,并且您想在索引2处插入一个字符串,您可以简单地使用JavaScript的数组splice方法:

var array = ['foo', 'bar', 1, 2, 3],
        insertAtIndex = 2,
        stringToBeInserted = 'someString';

// insert string 'someString' into the array at index 2
array.splice( insertAtIndex, 0, stringToBeInserted );

你的结果现在将是:

['foo', 'bar', 'someString', 1, 2, 3]

提示:你使用的push()方法只是将新项添加到数组的末尾(并返回新长度)。


10
请注意,splice函数返回一个空数组。splice直接将更改应用于数组。 - zed

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接