gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:41:41 24 4
gpt4 key购买 nike

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

例如,如果我通过 exampleFunc([1,2,3,4,5], 2) 它应该将所有项目向右移动 2 个位置,因此返回 [4,5,1,2,3]。我已经完成了以下操作,但是有没有更 Eloquent /有效的方法来做到这一点?此外,如果我想反转方向并浓缩为 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]

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]

最佳答案

您有要对数组进行切片并重新排列的位置的索引,因此您可以使用 .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]

.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]

也可以用.concat代替spread

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]

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]

关于JavaScript 按 X 数移动数组中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59556844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com