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

新手上路,请多包涵

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

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

[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) ,看到更好的实现会很有趣。

原文由 Moon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

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

  • unshift / push - 将元素添加到数组的开头/结尾

  • shift / pop - 删除并返回数组的第一个/最后一个元素

一个简单的图表…

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

和图表:

 add remove start end
 push XX
 pop XX
 unshift XX
 shift 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);

原文由 user229044 发布,翻译遵循 CC BY-SA 4.0 许可协议

数组操作图片

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

原文由 Mak 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题