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)
,看到更好的实现将真的很有趣。)
ask by Moon translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…