可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
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 and 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.
回答2:

var a = [23, 45, 12, 67]; a.unshift(34); console.log(a); // [34, 23, 45, 12, 67]
回答3:
With ES6 , use the spread operator ...
:
var arr=[23, 45, 12, 67] ; arr=[34, ...arr]; // RESULT : [34,23, 45, 12, 67]
回答4:
Another way to do that through 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.
function fn_unshift() { arr.unshift(0); return arr; } function fn_concat_init() { return [0].concat(arr) }
Here is the test result

回答5:
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.
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:
you have an array: var arr = [23, 45, 12, 67];
To add an item to the beginning, you want to use splice
: