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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32024319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:31:51  来源:igfitidea点击:

JS insert into array at specific index

javascriptarrays

提问by lilly

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

我想在特定索引处将字符串插入到数组中。我怎样才能做到这一点?

I tried to use push()

我尝试使用 push()

回答by nils

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:

嗯,这很容易。假设您有一个包含 5 个对象的数组,并且您想在索引 2 处插入一个字符串,您可以简单地使用 javascripts array 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 );

Your result will be now:

你的结果现在是:

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

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

仅供参考:您使用的 push() 方法只是将新项目添加到数组的末尾(并返回新长度)