如何在 Javascript 中的数组开头添加新的数组元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8073673/
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
How can I add new array elements at the beginning of an array in Javascript?
提问by Moon
I have a need to add or prepend elements at the beginning of an array.
我需要在数组的开头添加或添加元素。
For example, if my array looks like below:
例如,如果我的数组如下所示:
[23, 45, 12, 67]
And the response from my AJAX call is 34
, I want the updated array to be like the following:
我的 AJAX 调用的响应是34
,我希望更新后的数组如下所示:
[34, 23, 45, 12, 67]
Currently I am planning to do it like this:
目前我打算这样做:
var newArray = [];
newArray.push(response);
for (var i = 0; i < theArray.length; i++) {
newArray.push(theArray[i]);
}
theArray = newArray;
delete newArray;
Is there any better way to do this? Does Javascript have any built-in functionality that does this?
有没有更好的方法来做到这一点?Javascript 是否具有执行此操作的任何内置功能?
The complexity of my method is O(n)
and it would be really interesting to see better implementations.
我的方法很复杂,O(n)
看到更好的实现会很有趣。
回答by meagar
Use unshift
. It's like push
, except it adds elements to the beginning of the array instead of the end.
使用unshift
. 就像push
,除了它将元素添加到数组的开头而不是结尾。
unshift
/push
- add an element to the beginning/end of an arrayshift
/pop
- remove and return the first/last element of an array
unshift
/push
- 在数组的开头/结尾添加一个元素shift
/pop
- 删除并返回数组的第一个/最后一个元素
A simple diagram...
一个简单的图...
unshift -> array <- push
shift <- array -> pop
and chart:
和图表:
add remove start end
push X X
pop X X
unshift X X
shift X X
Check out the MDN Array documentation. Virtually every language that has the ability to push/pop elements from an array will also have the ability to unshift/shift (sometimes called push_front
/pop_front
) elements, you should never have to implement these yourself.
查看MDN 数组文档。实际上,每一种能够从数组中推送/弹出元素的语言也都能够取消/移动(有时称为push_front
/ pop_front
)元素,您永远不必自己实现这些。
As pointed out in the comments, if you want to avoid mutating your original array, you can use concat
, which concatenates two or more arrays together. You can use this to functionally push a single element onto the front or back of an existing array; to do so, you need to turn the new element into a single element array:
正如评论中指出的那样,如果您想避免改变原始数组,可以使用concat
,它将两个或多个数组连接在一起。您可以使用它在功能上将单个元素推送到现有数组的前面或后面;为此,您需要将新元素转换为单个元素数组:
const array = [ 3, 2, 1 ]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
concat
can also append items. The arguments to concat
can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:
concat
也可以追加项目。的参数concat
可以是任何类型;如果它们还不是数组,它们将被隐式包装在一个单元素数组中:
const array = [ 3, 2, 1 ]
const newLastElement = 0
// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]
回答by Maksym
var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]
回答by Abdennour TOUMI
With ES6 , use the spread operator ...
:
在 ES6 中,使用扩展运算符...
:
DEMO
演示
var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]
console.log(arr)
回答by zangw
Another way to do that through concat
另一种方法来做到这一点 concat
var arr = [1, 2, 3, 4, 5, 6, 7];
console.log([0].concat(arr));
The difference between concat
and unshift
is that concat
returns a new array. The performance between them could be found here.
之间的差concat
和unshift
是concat
返回一个新的数组。他们之间的表现可以在这里找到。
function fn_unshift() {
arr.unshift(0);
return arr;
}
function fn_concat_init() {
return [0].concat(arr)
}
Here is the test result
这是测试结果
回答by dreftymac
Quick Cheatsheet:
快速备忘单:
The terms shift/unshift and push/pop can be a bit confusing, at least to folks who may not be familiar with programming in C.
术语 shift/unshift 和 push/pop 可能有点令人困惑,至少对于可能不熟悉 C 编程的人来说是这样。
If you are not familiar with the lingo, here is a quick translation of alternate terms, which may be easier to remember:
如果您不熟悉该术语,这里是替代术语的快速翻译,可能更容易记住:
* array_unshift() - (aka Prepend ;; InsertBefore ;; InsertAtBegin )
* array_shift() - (aka UnPrepend ;; RemoveBefore ;; RemoveFromBegin )
* array_push() - (aka Append ;; InsertAfter ;; InsertAtEnd )
* array_pop() - (aka UnAppend ;; RemoveAfter ;; RemoveFromEnd )
回答by ozimax06
you have an array: var arr = [23, 45, 12, 67];
你有一个数组: var arr = [23, 45, 12, 67];
To add an item to the beginning, you want to use splice
:
要将项目添加到开头,您需要使用splice
:
var arr = [23, 45, 12, 67];
arr.splice(0, 0, 34)
console.log(arr);
回答by AmerllicA
Without Mutate
没有变异
Actually, all unshift
/push
and shift
/pop
mutatethe origin array.
实际上,所有unshift
/push
和shift
/ 都pop
改变了原点数组。
The unshift
/push
add an item to the existed array from begin/end and shift
/pop
remove an item from the beginning/end of an array.
的unshift
/push
将项目添加到从开始/结束和存在阵列shift
/pop
从数组的开始/结束删除项目。
But there are few ways to add items to an array without a mutation. the result is a new array, to add to the end of array use below code:
但是很少有方法可以在不发生突变的情况下将项目添加到数组中。结果是一个新数组,要添加到数组末尾,请使用以下代码:
const originArray = ['one', 'two', 'three'];
const newItem = 4;
const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+
To add to begin of original array use below code:
要添加到原始数组的开头,请使用以下代码:
const originArray = ['one', 'two', 'three'];
const newItem = 0;
const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+
With the above way, you add to the beginning/end of an array without a mutation.
通过上述方式,您可以在不进行突变的情况下添加到数组的开头/结尾。
回答by Tirkesh Turkesh
var testdata = new Array();
testdata = [23, 45, 12, 67];
testdata = [34, ...testdata];
console.log(testdata)
回答by Ben Adam
Using ES6 destructuring: (avoiding mutation off the original array)
使用 ES6 解构:(避免改变原始数组)
const newArr = [item, ...oldArr]
const newArr = [item, ...oldArr]
回答by Jenny O'Reilly
If you need to continuously insert an element at the beginning of an array, it is faster to use push
statements followed by a call to reverse
, instead of calling unshift
all the time.
如果你在一个数组的开头需要不断插入一个元素,它是更快地使用push
发言,然后是到呼叫reverse
,而不是调用unshift
所有的时间。
Benchmark test:http://jsben.ch/kLIYf
基准测试:http : //jsben.ch/kLIYf