Javascript javascript在数组的开头推送元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8159524/
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
javascript pushing element at the beginning of an array
提问by frenchie
I have an array of objects and I'd like to push an element at the beginning of the of the array.
我有一个对象数组,我想在数组的开头推送一个元素。
I have this:
我有这个:
var TheArray = TheObjects.Array;
TheArray.push(TheNewObject);
It's adding TheNewObject at the end. Do I need to create a new array, add TheNewObject to it and then loop through TheArray and add each element the to the array?
它在最后添加了 TheNewObject。我是否需要创建一个新数组,向其中添加 TheNewObject,然后遍历 TheArray 并将每个元素添加到数组中?
回答by lonesomeday
回答by jfriend00
Use .unshift()
to add to the beginning of an array.
使用.unshift()
添加到一个数组的开始。
TheArray.unshift(TheNewObject);
See MDN for doc on unshift()
and here for doc on other array methods.
有关其他数组方法的文档,unshift()
请参阅 MDN和此处的文档。
FYI, just like there's .push()
and .pop()
for the end of the array, there's .shift()
and .unshift()
for the beginning of the array.
仅供参考,就像有.push()
和.pop()
为数组的结尾,有.shift()
和.unshift()
为数组的开始。
回答by Wayne
For an uglier version of unshift
use splice
:
对于更丑陋的unshift
使用版本splice
:
TheArray.splice(0, 0, TheNewObject);