欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-15 11:03:46
...

本文翻译自: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 这是测试结果

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


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

相关标签: javascript arrays