繁体   English   中英

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

[英]JavaScript move along all items in array by X number

我想创建一个接受 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]

 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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM