JS在特定索引处插入到数组中

JS在特定索引处插入到数组中

问题描述:

我想在特定索引处的数组中插入一个字符串。我怎么能这样做?

I would like to insert a string into an array at a specific index. How can I do that?

我试图使用push()

I tried to use push()

嗯,这很容易。假设你有一个包含5个对象的数组,你想在索引2处插入一个字符串,你只需使用javascripts数组拼接方法:

Well, thats pretty easy. Assuming you have an array with 5 objects inside and you want to insert a string at index 2 you can simply use javascripts array splice method:

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]

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

FYI: The push() method you used just adds new items to the end of an array (and returns the new length)