如何在Javascript數組的開頭添加新的數組元素?

本文翻譯自:How can I add new array elements at the beginning of an array in Javascript?

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) ,看到更好的實現將真的很有趣。


#1樓

參考:https://stackoom.com/question/XsKX/如何在Javascript數組的開頭添加新的數組元素


#2樓

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. 術語“移位/不移位”和“推入/彈出”可能會有些混亂,至少對於那些可能不熟悉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 ) 

#3樓

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


#4樓

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. 之間的差concatunshiftconcat返回一個新的數組。 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樓

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) 


#6樓

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章