How can I add new array elements at the beginning

2018-12-31 19:32发布

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:

[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?

The complexity of my method is O(n) and it would be really interesting to see better implementations.

11条回答
梦寄多情
2楼-- · 2018-12-31 19:47

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

  • unshift/push - add an element to the beginning/end of an array
  • shift/pop - remove and return the first/last element of an array

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.

查看更多
心情的温度
3楼-- · 2018-12-31 19:48

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

查看更多
冷夜・残月
4楼-- · 2018-12-31 19:50

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)

查看更多
浪荡孟婆
5楼-- · 2018-12-31 19:51

array operations image

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

查看更多
唯独是你
6楼-- · 2018-12-31 19:55

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

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

use theArray.unshift(response)

查看更多
琉璃瓶的回忆
7楼-- · 2018-12-31 19:58

Using push, splice, and index number we insert an element to an array at first

arrName.push('newName1');
arrName.splice(0, 0,'newName1');
arrName[0] = 'newName1';
查看更多
登录 后发表回答