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

发布于 2024-12-14 14:24:12 字数 490 浏览 0 评论 0原文

我需要在数组的开头添加或添加元素。

例如,如果我的数组如下所示:

[23, 45, 12, 67]

并且我的 AJAX 调用的响应是 34,我希望更新后的数组如下所示:

[34, 23, 45, 12, 67]

目前我计划这样做

var newArray = [];
newArray.push(response);

for (var i = 0; i < theArray.length; i++) {
    newArray.push(theArray[i]);
}

theArray = newArray;
delete newArray;

:有更好的方法吗? JavaScript 是否有任何内置功能可以做到这一点?

我的方法的复杂度是O(n),看到更好的实现将会非常有趣。

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 a 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

懒的傷心 2024-12-21 14:24:12

使用unshift。它类似于 push,只不过它将元素添加到数组的开头而不是结尾。

  • unshift/push - 将元素添加到数组的开头/结尾
  • shift/pop - 删除并返回数组的第一个/最后一个元素

一个简单的图表...

unshift -> [array] <- push
shift   <- [array] -> pop

和图表:

 添加删除开始结束
pushXX
popXX
取消移动XX
移动XX

查看 MDN 数组文档。实际上,每种能够从数组中推送/弹出元素的语言也都能够取消移位/移位(有时称为 push_front/pop_front)元素,但你永远不应该必须自己实施这些。


正如评论中指出的,如果您想避免改变原始数组,可以使用 concat,将两个或多个数组连接在一起。您可以使用它在功能上将单个元素推送到现有数组的前面或后面;为此,您需要将新元素转换为单个元素数组:

const array = [3, 2, 1]

const newFirstElement = 4

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

console.log(newArray);

concat 也可以追加项目。 concat 的参数可以是任何类型;如果它们还不是数组,则它们隐式包装在单元素数组中:

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

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:

 addremovestartend
pushXX
popXX
unshiftXX
shiftXX

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.


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. 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. The arguments to concat can be of any type; 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);

焚却相思 2024-12-21 14:24:12

数组操作图像

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

array operations image

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

浅暮の光 2024-12-21 14:24:12

对于 ES6,使用展开运算符 ...

演示

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

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)

孤芳又自赏 2024-12-21 14:24:12

另一种方法是通过 concat

var arr = [1, 2, 3, 4, 5, 6, 7];
console.log([0].concat(arr));

concatunshift 之间的区别在于 concat 返回一个新数组。它们之间的性能可以在此处找到。

function fn_unshift() {
  arr.unshift(0);
  return arr;
}

function fn_concat_init() {
  return [0].concat(arr)
}

这是测试结果:

在此输入图像描述

Another way to do that is 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:

Enter image description here

绿光 2024-12-21 14:24:12

快速备忘单:

术语“shift/unshift”和“push/pop”可能有点令人困惑,至少对于不熟悉 C 语言编程的人来说

是这样。如果您不熟悉术语,请参阅以下内容替代术语的快速翻译,可能更容易记住:

* array_unshift()  -  (aka Prepend ;; InsertBefore ;; InsertAtBegin )     
* array_shift()    -  (aka UnPrepend ;; RemoveBefore  ;; RemoveFromBegin )

* array_push()     -  (aka Append ;; InsertAfter   ;; InsertAtEnd )     
* array_pop()      -  (aka UnAppend ;; RemoveAfter   ;; RemoveFromEnd ) 

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 ) 
山川志 2024-12-21 14:24:12

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

const newArr = [项目, ...oldArr]

Using ES6 destructuring (avoiding mutation off the original array):

const newArr = [item, ...oldArr]

小糖芽 2024-12-21 14:24:12

您有一个数组: var arr = [23, 45, 12, 67];

要将项目添加到开头,您需要使用 splice:

var arr = [23, 45, 12, 67];
arr.splice(0, 0, 34)
console.log(arr);

You have an array: var arr = [23, 45, 12, 67];

To add an item to the beginning, you want to use splice:

var arr = [23, 45, 12, 67];
arr.splice(0, 0, 34)
console.log(arr);

昇り龍 2024-12-21 14:24:12

没有变异

实际上,所有unshift/pushshift/pop 改变源数组。

unshift/push 从 begin/end 向现有数组添加一个项目,shift/pop 删除一个项目从数组的开头/结尾开始。

但是,几乎没有什么方法可以在不进行突变的情况下将项目添加到数组中。结果是一个新数组,要添加到数组的末尾,请使用以下代码:

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

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

要添加到原始数组的开头,请使用以下代码:

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

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

通过上述方式,您可以添加到数组的开头/结尾而不进行突变。

Without Mutating

Actually, all unshift/push and shift/pop mutate the source array.

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.

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.

绝不服输 2024-12-21 14:24:12

在数组中添加新元素的备忘单

1. Array#unshift< /a>

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

list.unshift(34);

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

2. Array#splice< /a>

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

list.splice(0, 0, 34);

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

3. ES6 传播...

const list = [23, 45, 12, 67];
const newList = [34, ...list];

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

4. Array#concat< /a>

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

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

注意:在每个示例中,您可以通过提供更多要插入的项目来添加多个项目。

Cheatsheet to prepend new element(s) into the array

1. Array#unshift

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

list.unshift(34);

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

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...

const list = [23, 45, 12, 67];
const newList = [34, ...list];

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

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.

单挑你×的.吻 2024-12-21 14:24:12

如果需要在数组开头连续插入元素,使用 push 语句并随后调用 reverse 会比调用 unshift 更快一直以来。

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

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.

Benchmark test: http://jsben.ch/kLIYf

我还不会笑 2024-12-21 14:24:12

使用 splice 我们在数组的开头插入一个元素:

arrName.splice( 0, 0, 'newName1' );

Using splice we insert an element to an array at the begnning:

arrName.splice( 0, 0, 'newName1' );
久伴你 2024-12-21 14:24:12

如果要将数组中的元素推送到数组开头,请​​使用 .apply(,)

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

If you want to push elements that are in an array at the beginning of your array, use <func>.apply(<this>, <Array of args>):

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文