简体   繁体   English

如何在 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 a 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) ,如果能看到更好的实现会非常有趣。

Use unshift .使用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 an 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 .查看MDN 阵列文档 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.几乎每一种能够从数组中推送/弹出元素的语言也将能够取消移动/移动(有时称为push_front / pop_front )元素,您永远不必自己实现这些。


As pointed out in the comments, if you want to avoid mutating your original array, you can use concat , which concatenates two or more arrays together.正如评论中所指出的,如果你想避免改变你的原始数组,你可以使用concat ,它将两个或多个数组连接在一起。 You can use this to functionally push a single element onto the front or back of an existing array;您可以使用它在功能上将单个元素推送到现有数组的前面或后面; to do so, you need to turn the new element into a single element array:为此,您需要将新元素转换为单个元素数组:

 const array = [3, 2, 1] const newFirstElement = 4 const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ] console.log(newArray);

concat can also append items. concat还可以附加项目。 The arguments to concat can be of any type; concat的参数可以是任何类型; they are implicitly wrapped in a single-element array, if they are not already an array:如果它们还不是数组,则它们被隐式包装在单元素数组中:

 const array = [3, 2, 1] const newLastElement = 0 // Both of these lines are equivalent: const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ] const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ] console.log(newArray1); console.log(newArray2);

数组操作图像

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

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)

Another way to do that is 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. concatunshift的区别在于concat返回一个新数组。 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:这是测试结果:

在此处输入图像描述

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.术语 shift/unshift 和 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 ) 

使用 ES6 解构(避免原始数组的突变):

const newArr = [item, ...oldArr]

Without Mutating没有变异

Actually, all unshift / push and shift / pop mutate the source array.实际上,所有unshift / pushshift / pop都会改变源数组。

The unshift / push add an item to the existed array from begin/end and shift / pop remove an item from the beginning/end of an array. unshift / push从开始/结束向现有数组添加一个项目,而shift / pop从数组的开始/结束删除一个项目。

But there are few ways to add items to an array without a mutation.但是很少有方法可以在没有突变的情况下将项目添加到数组中。 the result is a new array, to add to the end of array use below code:结果是一个新数组,要添加到数组末尾,请使用以下代码:

const originArray = ['one', 'two', 'three'];
const newItem = 4;

const newArray = originArray.concat(newItem); // ES5
const newArray2 = [...originArray, newItem]; // ES6+

To add to begin of original array use below code:要添加到原始数组的开头,请使用以下代码:

const originArray = ['one', 'two', 'three'];
const newItem = 0;

const newArray = (originArray.slice().reverse().concat(newItem)).reverse(); // ES5
const newArray2 = [newItem, ...originArray]; // ES6+

With the above way, you add to the beginning/end of an array without a mutation.通过上述方式,您可以添加到数组的开头/结尾而没有突变。

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

Cheatsheet to prepend new element(s) into the array备忘单将新元素添加到数组中

1. Array#unshift 1. Array#unshift

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

2. Array#splice 2. Array#splice

 const list = [23, 45, 12, 67]; list.splice(0, 0, 34); console.log(list); // [34, 23, 45, 12, 67];

3. ES6 spread... 3. ES6 传播...

 const list = [23, 45, 12, 67]; const newList = [34, ...list]; console.log(newList); // [34, 23, 45, 12, 67];

4. Array#concat 4. Array#concat

 const list = [23, 45, 12, 67]; const newList = [32].concat(list); console.log(newList); // [34, 23, 45, 12, 67];

Note: In each of these examples, you can prepend multiple items by providing more items to insert.注意:在每个示例中,您可以通过提供更多要插入的项目来预先添加多个项目。

push() adds a new element to the end of an array. push()将新元素添加到数组的末尾。
pop() removes an element from the end of an array. pop()从数组末尾删除元素。

unshift() adds a new element to the beginning of an array. unshift()将新元素添加到数组的开头。
shift() removes an element from the beginning of an array. shift()从数组的开头删除一个元素。

use theArray.unshift(response) 使用theArray.unshift(response)

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

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

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

使用splice我们在开始时将元素插入到数组中:

arrName.splice( 0, 0, 'newName1' );
var array = [23, 45, 12, 67];  
array.unshift(11);  
alert(array);

Pop, Push, Shift and Unshift Array Methods in JavaScript JavaScript gives us four methods to add or remove items from the beginning or end of arrays: JavaScript 中的 Pop、Push、Shift 和 Unshift 数组方法 JavaScript 为我们提供了四种方法来在数组的开头或结尾添加或删除项目:

pop() : Remove an item from the end of an array pop() : 从数组的末尾删除一个项目

let cats = ['Bob', 'Willy', 'Mini'];

cats.pop(); // ['Bob', 'Willy']

pop() returns the removed item. pop() 返回删除的项目。

push() : Add items to the end of an array push() : 将元素添加到数组的末尾

let cats = ['Bob'];

cats.push('Willy'); // ['Bob', 'Willy']

cats.push('Puff', 'George'); // ['Bob', 'Willy', 'Puff', 'George']
push() returns the new array length.

shift() : Remove an item from the beginning of an array shift() :从数组的开头删除一个项目

let cats = ['Bob', 'Willy', 'Mini'];

cats.shift(); // ['Willy', 'Mini']
shift() returns the removed item.

unshift() : Add items to the beginning of an array unshift() :将项目添加到数组的开头

let cats = ['Bob'];

cats.unshift('Willy'); // ['Willy', 'Bob']

cats.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Bob']

If you want to push elements that are in an array at the beginning of your array, use <func>.apply(<this>, <Array of args>) :如果要在数组开头推送数组中的元素,请使用<func>.apply(<this>, <Array of args>)

 const arr = [1, 2]; arr.unshift.apply(arr, [3, 4]); console.log(arr); // [3, 4, 1, 2]

There are a couple of ways to achieve this:有几种方法可以实现这一点:

  1. Using shift (mutable)使用移位(可变)

 const num = 1; const arr = [2, 3]; arr.unshift(num); console.log(arr);

  1. Using ES6 destructuring (immutable)使用 ES6 解构(不可变)

 const num = 1; const arr = [2, 3]; const newArr = [num, ...arr]; console.log(newArr);

  1. Using Array.prototype.concat (immutable)使用Array.prototype.concat (不可变)

 const num = 1; const arr = [2, 3]; const newArr = [num].concat(arr); console.log(newArr);

you can first reverse array and then add elem to array then reverse back it.您可以先反转数组,然后将 elem 添加到数组中,然后将其反转回来。

const arr = [2,3,4,5,6];
const arr2 = 1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

console.log(arr.reverse()); // [1,2,3,4,5,6]

good lock好锁

ali alizadeh.阿里·阿里扎德

 let arr = [5, 6]; // using unshift arr.unshift(4); console.log('arr : ', arr); // using spread operator arr = [3, ...arr]; console.log('arr : ', arr); // using concat arr = [2].concat(arr); console.log('arr : ', arr); // using splice arr.splice(0, 0, 1) console.log('arr : ', arr);

Performance: For small arrays you can choose whichever you want, no significant performance difference.性能:对于小型阵列,您可以随意选择,没有显着的性能差异。 But for some tens of items, unshift() is much better than anything else.但是对于几十个项目, unshift() 比其他任何东西都要好得多。

See results here: https://jsben.ch/GDA3P在此处查看结果: https : //jsben.ch/GDA3P

Use unshift function.使用unshift功能。 It will push element at beginning of the array它将在数组的开头推送元素

var list = [23, 45, 12, 67];

list.unshift(34);

// It will return [34, 23, 45, 12, 67];

"array.unshift()" is a method which is use to add elements at the start of an array. “array.unshift()”是一种用于在数组开头添加元素的方法。

The guide is in the link below.该指南在下面的链接中。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

 let array = [23, 45, 12, 67]; array.unshift(12); console.log(array);

you can reverse your array and push the data , at the end again reverse it:您可以反转数组并推送数据,最后再次反转它:

var arr=[2,3,4,5,6];
var arr2=1;
arr.reverse();
//[6,5,4,3,2]
arr.push(arr2);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM