javascript-将第一个元素移到数组末尾的最快方法
我想知道JavaScript中将元素从shift()的开头移到结尾的最快方法是什么。 例如,如果我们有
shift()
我们想要:shift()
我想将第一个元素移到末尾。 我正在考虑用元素1切换元素0,然后再用元素2切换元素1,依此类推,直到元素8和为止(基本上是bubblesort的工作方式)。 我想知道是否有更快的方法将第一个元素放到最后。
我将使用小型数组(大约10个元素),并且我想避免shift(),因为它非常慢。
这就是我现在在chrome上看到的内容,它比正常的shift + push速度快45%:[http://jsperf.com/shift-myfunc]
数组将在其中包含用于游戏的对象。
8个解决方案
84 votes
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
jsFiddle示例
var ary = [8,1,2,3,4,5,6,7];
console.log("Before: " + ary);
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
console.log("After: " + ary);
j08691 answered 2020-07-13T19:58:49Z
22 votes
使用concat()和concat()
var a = ["a","b","c"];
var b = a.shift();
a.push(b);
要么
var b = a.shift();
a[a.length] = b;
根据更新的问题进行编辑
什么是最快的? 确实取决于数组的内容以及什么浏览器/版本!
现在,删除第一个索引的方法是什么?
concat()
concat()
concat()
现在添加到最后一个索引的方法是什么?
concat()
concat()
concat()-甚至都不会尝试
其他方法
for循环-制作新数组[在大型数组上将变得可怕]
JSPerf:
[HTTP://JSP而F.com/test-swapping-of-first-to-last]
真正最快的是什么?
最快的速度实际上取决于您对阵列执行的操作。 如果您仅使用第一个索引,那么使您的代码读取索引而不移动值将是最快的。 如果您正在使用所有索引,则不只是循环遍历,直到结束时才从零开始。 基本柜台。
epascarello answered 2020-07-13T20:00:01Z
7 votes
使用拼接获取第一个元素
var first = array.splice(0,1);
然后推动以使最后。
由于splice方法的返回值是一个数组,因此必须说
array.push(first[0]);
这里的工作示例:JSFIDDLE
Felipe Fonseca answered 2020-07-13T20:00:34Z
7 votes
万一您想将任何元素放在最后:
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.splice(position, 1)[0]);
为position只需将其包装在forEach中即可。
artdias90 answered 2020-07-13T20:00:58Z
5 votes
这是一个不错的ES6版本
let arr = [1,2,3,4,5,6]
const [first, ...rest] = arr;
arr = [...rest,first]
Nicholas answered 2020-07-13T20:01:18Z
3 votes
var a = [1,2,3,4,5,6,7,8];
var b= a[7];
var c = a.slice(1, 8);
c.push(b);
编辑:最好移动一下,就像epascarello在他的回答中所做的那样。
Jeroen Bollen answered 2020-07-13T20:01:38Z
1 votes
一种口味
var arr = [0, 1, 2];
arr = arr.concat(arr.shift())
concat不仅可以在一个元素的末尾添加一个元素,还可以添加另一个数组
MohitGhodasara answered 2020-07-13T20:02:02Z
0 votes
更新将元素从一个极端移动到另一个极端的数组:
const array = ['First', 'Second', 'Third', 'Fourth'];
const next = [...array]
next.push(next.shift())
console.log(next); // [ 'Second', 'Third', 'Fourth', 'First' ]
const prev = [...array]
prev.unshift(prev.pop())
console.log(prev); // [ 'Fourth', 'First', 'Second', 'Third' ]
feralamillo answered 2020-07-13T20:02:22Z