如何推送到数组的特定位置?
我正在尝试有效地编写一条语句,将其推入数组的位置 1,并将该位置中的任何内容推入该位置,或者将其推回某个位置。
array = [4,5,9,6,2,5]
#push 0 to position 1
array = [4,0,5,9,6,2,5]
#push 123 to position 1
array = [4,123,0,5,9,6,2,5]
写这个的最好方法是什么? (可接受 JavaScript 或 CoffeeScript)
谢谢!
I'm trying to efficiently write a statement that pushes to position 1 of an array, and pushes whatever is in that position, or after it back a spot.
array = [4,5,9,6,2,5]
#push 0 to position 1
array = [4,0,5,9,6,2,5]
#push 123 to position 1
array = [4,123,0,5,9,6,2,5]
What is the best way to write this? (javascript or coffeescript acceptable)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
splice()
函数是唯一一个原生数组函数,可让您将元素添加到数组的特定位置我将获得您在问题中输入的一个数组来进行描述
position
= 您要添加新项目的位置numberOfItemsToRemove
= 这表示要删除的项目数量。那是表示删除将按照新项目添加的位置开始。
item
= 您添加的新项目The
splice()
function is the only native array function that lets you add elements to the specific place of an arrayI will get a one array that you entered in your question to describe
position
= What is the position that you want to add new itemnumberOfItemsToRemove
= This indicate how many number of items will deleted. That'smean delete will start according to the position that new item add.
item
= the new item that you add你不能只是这样做:
你将需要一个具有适当大小的数组,但我不确定在没有请求的索引的列表上进行拼接的行为是什么。
Could you not just do:
You will need to have an array with the appropriate size, but I'm not sure what the behavior for splice on a list that doesn't have the requested index is either.