为什么我尝试在javascript中旋转此数组导致索引被跳过[关闭]

问题描述 投票:0回答:4

let arr = [1, 2, 3, 4, 5]
let steps = 2
let hold = arr
let indlength = arr.length - 1
for (let i = indlength; i > indlength - steps; i--) {
  hold.unshift(arr[i])
  hold.pop()
}

console.log(hold)

所以我试图将这个数组在javascript中向右旋转2个旋转。而不是得到4,5,1,2,3我得到3,5,1,2,3。我怀疑它与被跳过的索引有关,因为如果我将步骤设置为3,它将变为1,3,5,1,2。这是一个repl链接https://repl.it/@helixlamont/ExoticTealOpengl

javascript arrays methods rotation pop
4个回答
1
投票

问题是当你这样做时你要保留的参考let hold = arr;你应该创建一个arr的真实副本/克隆。

另一种方法是使用spread-syntax

let arr = [1, 2, 3, 4, 5],
    steps = 2,
    hold = [...arr],
    indlength = arr.length - 1;

for (let i = indlength; i > indlength - steps; i--) {
  hold.unshift(arr[i]);
  hold.pop();
}

console.log(hold)
.as-console-wrapper { max-height: 100% !important; top: 0; }

0
投票

在您的代码问题中,您在let hold = arr中使用了arr的引用。

Ele's answer已经添加了代码的工作片段。

其他方式是使用spliceconcat

let arr = [1,2,3,4,5]
let steps = 2
let part1 = arr.splice(-steps)

console.log(part1.concat(arr))

0
投票

您的代码无法正常工作,因为您更改了取消该值的索引。它从最后一个索引开始,然后变为零。结果是一些缺失的值。

通过始终使用最后一个索引,您可以得到想要的结果。


我不会使用一个数组作为源并使用相同的对象引用操纵另一个数组。为了保持一致的方法,我只使用其中一个。

let arr = [1, 2, 3, 4, 5]
let steps = 2
let hold = arr
let indlength = arr.length - 1
for (let i = indlength; i > indlength - steps; i--) {
  console.log(hold.join(' '));
  hold.unshift(hold[indlength]); // take the last value and use hold instead of arr
  hold.pop();
}

console.log(hold.join(' '));

简化版本是弹出(最后一个值)并取消它(在数组的前面)。数组的长度是恒定的。

let array = [1, 2, 3, 4, 5],
    steps = 2,
    i;

for (i = 0; i < steps; i++) {
    console.log(array.join(' '));
    array.unshift(array.pop());        
}

console.log(array.join(' '));

0
投票

其他人已经描述了为什么你的代码不起作用。一个简单的非变异替代方案是

const rotate = (steps, arr) => arr.slice(-steps).concat(arr.slice(0, -steps))

console.log(rotate(2, [1, 2, 3, 4, 5]))
console.log(rotate(-1, [1, 2, 3, 4, 5]))

如果你想向另一个方向旋转,你可以放弃否定标志。

如果steps大于数组的长度,则会失败。如果你想让它继续旋转,那就不难了:

const rotate = (steps, arr) => 
  arr.slice(-(steps % arr.length)).concat(arr.slice(0, -(steps % arr.length)))
© www.soinside.com 2019 - 2024. All rights reserved.