我怎么能在JavaScript的数组的开头添加新的数组元素? [英] How can I add new array elements at the beginning of an array in JavaScript?

查看:185
本文介绍了我怎么能在JavaScript的数组的开头添加新的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要添加元素(我检索使用AJAX及时的基础上)在阵列的顶端。

I have a need to add elements (I retrieve on timely basis using AJAX) at the top of an array.

例如,如果我的数组类似如下:

For example, if my array looks like below:

[23, 45, 12, 67]

和从我的AJAX调用的响应是 34 ,我想更新的数组是这样的:

And the response from my AJAX call is 34, I want the updated array to be like the following:

[34, 23, 45, 12, 67]

目前我打算做这样的:

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

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

theArray = newArray;
delete newArray;

有没有什么更好的方法来做到这一点? JavaScript的是否有任何内置的功能,做到这一点?

Is there any better way to do this? Does JavaScript have any built-in functionality that does this?

我的方法的复杂性是 O(N)键,看到更好的实现这将是非常有趣的。

The complexity of my method is O(n) and it would be really interesting to see better implementations.

推荐答案

使用<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift\"><$c$c>unshift.这就像<一个href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push\"><$c$c>push,除了它添加元素的数组,而不是结束的开始。

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 and array

一个简单的图...

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

和图:

          add  remove  start  end
   push    X                   X
    pop           X            X
unshift    X             X
  shift           X      X

查看 MDN阵列文档。几乎每一个有推动能力,语言/从数组中的流行元素也将有不印字/班的能力(有时也称为 push_front / pop_front )的元素,你不应该来实现这些自己。

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.

这篇关于我怎么能在JavaScript的数组的开头添加新的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆