JS在特定索引处插入到数组中 [英] JS insert into array at specific index
本文介绍了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)
这篇关于JS在特定索引处插入到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文