JavaScript 按 X 号沿数组中的所有项目移动

JS_*_*Dev 3 javascript arrays

我想创建一个接受 2 个参数的函数,第一个参数是一个数组,第二个参数是移动所有数组项的索引位置数。

因此,例如,如果我通过 exampleFunc([1,2,3,4,5], 2) 它应该将所有项目向右移动 2 个位置,因此返回 [4,5,1,2,3]。我已经完成了以下操作,但是有没有更雄辩/有效的方法来做到这一点?另外,如果我想反转方向并将其压缩为 1 个函数而不是如下所示的两个函数,除了在每个函数的不同部分放置条件之外,还有什么建议吗?尝试使用 .splice() 方法,但并没有真正到任何地方。任何帮助将不胜感激!

const moveArrayPositionRight = (array, movePositions) => {
  let newArray = new Array(array.length);

  for (i = 0; i < array.length; i++) {
    let newIndex = i - movePositions;

    if (newIndex < 0) {
      newIndex += array.length;
    }

    newArray[i] = array[newIndex];
  }

  return newArray;
};

console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 2)); // output: [8, 10, 2, 4, 6]
Run Code Online (Sandbox Code Playgroud)

const moveArrayPositionLeft = (array, movePositions) => {
  let newArray = new Array(array.length);

  for (i = 0; i < array.length; i++) {
    let newIndex = i - movePositions;

    if (newIndex < 0) {
      newIndex += array.length - 1;
    }

    newArray[i] = array[newIndex];
  }

  return newArray;
};

console.log(moveArrayPositionLeft([3, 6, 9, 12, 15], 2)); // output: [9,12,15,3,6]
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 7

您拥有要对数组进行切片并重新排列的位置的索引,因此您可以使用它.slice来做到这一点 - 提取需要重新排列的子数组,然后放入一个新数组中:

const moveArrayPositionRight = (array, movePositions) => [
  ...array.slice(array.length - movePositions),
  ...array.slice(0, array.length - movePositions)
];

console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 2)); // output: [8, 10, 2, 4, 6]
console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 3)); // expected [6, 8, 10, 2, 4]
Run Code Online (Sandbox Code Playgroud)

.slice 也可以采用负指数从末尾而不是从头开始切片:

const moveArrayPositionRight = (array, movePositions) => [
  ...array.slice(-movePositions),
  ...array.slice(0, -movePositions)
];

console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 2)); // output: [8, 10, 2, 4, 6]
console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 3)); // expected [6, 8, 10, 2, 4]
Run Code Online (Sandbox Code Playgroud)

也可以使用.concat代替传播

const moveArrayPositionRight = (array, movePositions) => array
  .slice(array.length - movePositions)
  .concat(array.slice(0, array.length - movePositions));

console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 2)); // output: [8, 10, 2, 4, 6]
console.log(moveArrayPositionRight([2, 4, 6, 8, 10], 3)); // expected [6, 8, 10, 2, 4]
Run Code Online (Sandbox Code Playgroud)

同样的事情moveArrayPositionLeft

const moveArrayPositionLeft = (array, movePositions) => [
  ...array.slice(movePositions),
  ...array.slice(0, movePositions)
];

console.log(moveArrayPositionLeft([3, 6, 9, 12, 15], 2)); // output: [9,12,15,3,6]
Run Code Online (Sandbox Code Playgroud)