如何在JavaScript数组的开头添加新的数组元素?

时间:2022-02-27 03:19:15

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),看到更好的实现会非常有趣。

9 个解决方案

#1


2086  

Use unshift. It's like push, except it adds elements to the beginning of the array instead of the end.

使用平移。这就像push,只不过它将元素添加到数组的开头而不是结束。

  • unshift/push - add an element to the beginning/end of an array
  • unshift/push——向数组的开头/结尾添加一个元素
  • shift/pop - remove and return the first/last element of and array
  • 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)元素,您不应该自己实现这些元素。

#2


1146  

如何在JavaScript数组的开头添加新的数组元素?

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

#3


118  

With ES6 , use the spread operator ... :

DEMO

演示

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

#4


48  

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

这是测试结果

如何在JavaScript数组的开头添加新的数组元素?

#5


37  

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.

术语转换/不移位和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 ) 

#6


13  

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);

#7


1  

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

push()将一个新元素添加到数组的末尾。pop()从数组末尾删除一个元素。

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

unshift()在数组的开头添加一个新元素。shift()从数组的开头删除一个元素。

use theArray.unshift(response)

使用theArray.unshift(响应)

#8


1  

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语句然后调用反向会更快,而不是一直调用unshift。

Benchmark test: http://jsben.ch/kLIYf

基准测试:http://jsben.ch/kLIYf

#9


0  

var testdata = new Array();
testdata = [23, 45, 12, 67];
testdata = [34, ...testdata]; 
console.log(testdata)
    

#1


2086  

Use unshift. It's like push, except it adds elements to the beginning of the array instead of the end.

使用平移。这就像push,只不过它将元素添加到数组的开头而不是结束。

  • unshift/push - add an element to the beginning/end of an array
  • unshift/push——向数组的开头/结尾添加一个元素
  • shift/pop - remove and return the first/last element of and array
  • 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)元素,您不应该自己实现这些元素。

#2


1146  

如何在JavaScript数组的开头添加新的数组元素?

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

#3


118  

With ES6 , use the spread operator ... :

DEMO

演示

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

#4


48  

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

这是测试结果

如何在JavaScript数组的开头添加新的数组元素?

#5


37  

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.

术语转换/不移位和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 ) 

#6


13  

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);

#7


1  

push() adds a new element to the end of an array.
pop() removes an element from the end of an array.

push()将一个新元素添加到数组的末尾。pop()从数组末尾删除一个元素。

unshift() adds a new element to the beginning of an array.
shift() removes an element from the beginning of an array.

unshift()在数组的开头添加一个新元素。shift()从数组的开头删除一个元素。

use theArray.unshift(response)

使用theArray.unshift(响应)

#8


1  

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语句然后调用反向会更快,而不是一直调用unshift。

Benchmark test: http://jsben.ch/kLIYf

基准测试:http://jsben.ch/kLIYf

#9


0  

var testdata = new Array();
testdata = [23, 45, 12, 67];
testdata = [34, ...testdata]; 
console.log(testdata)