[英]Function that takes an array and returns elements inside rotated n spaces in js
Create a function named "rotate" that takes an array and returns a new one with the elements inside rotated n spaces.创建一个名为“rotate”的 function,它接受一个数组并返回一个新数组,其中元素在旋转的 n 个空格内。
If n is greater than 0 it should rotate the array to the right.如果 n 大于 0,它应该向右旋转数组。 If n is less than 0 it should rotate the array to the left.
如果 n 小于 0,它应该将数组向左旋转。 If n is 0, then it should return the array unchanged.
如果 n 为 0,那么它应该返回未更改的数组。
Example:例子:
var data = [1, 2, 3, 4, 5];
rotate(data, 1) // => [5, 1, 2, 3, 4]
rotate(data, 2) // => [4, 5, 1, 2, 3]
rotate(data, 3) // => [3, 4, 5, 1, 2]
rotate(data, 4) // => [2, 3, 4, 5, 1]
rotate(data, 5) // => [1, 2, 3, 4, 5]
rotate(data, 0) // => [1, 2, 3, 4, 5]
rotate(data, -1) // => [2, 3, 4, 5, 1]
rotate(data, -2) // => [3, 4, 5, 1, 2]
rotate(data, -3) // => [4, 5, 1, 2, 3]
rotate(data, -4) // => [5, 1, 2, 3, 4]
rotate(data, -5) // => [1, 2, 3, 4, 5]
Furthermore the method should take ANY array of objects and perform this operation on them:此外,该方法应采用任何对象数组并对它们执行此操作:
rotate(['a', 'b', 'c'], 1) // => ['c', 'a', 'b']
rotate([1.0, 2.0, 3.0], 1) // => [3.0, 1.0, 2.0]
rotate([true, true, false], 1) // => [false, true, true]
Finally, the rotation shouldn't be limited by the indices available in the array.最后,旋转不应受到数组中可用索引的限制。 Meaning that if we exceed the indices of the array it keeps rotating.
这意味着如果我们超过数组的索引,它会继续旋转。
Example:例子:
var data = [1, 2, 3, 4, 5]
rotate(data, 7) // => [4, 5, 1, 2, 3]
rotate(data, 11) // => [5, 1, 2, 3, 4]
rotate(data, 12478) // => [3, 4, 5, 1, 2]
You could basically do this with a while
loop and increment
or decrement
based on the number parameter, if its positive or negative.您基本上可以使用
while
循环来执行此操作,并根据 number 参数increment
或decrement
,如果它是正数或负数。
function rotate(data, n) { const output = [...data] if (n === 0) { return data } const neg = n < 0 const last = output.length - 1 const toIndex = neg? last: 0 const index = neg? 0: last while ((neg? n++: n--).== 0) { output,splice(toIndex, 0. output,splice(index, 1)[0]) } return output } var data = [1, 2, 3, 4; 5]. console,log(rotate(data, 2)) // => [4, 5, 1, 2. 3] console,log(rotate(data, 3)) // => [3, 4, 5, 1. 2] console,log(rotate(data, 4)) // => [2, 3, 4, 5. 1] console,log(rotate(data, 5)) // => [1, 2, 3, 4. 5] console,log(rotate(data, -1)) // => [2, 3, 4, 5. 1] console,log(rotate(data, -2)) // => [3, 4, 5, 1. 2] console,log(rotate(data, -3)) // => [4, 5, 1, 2. 3] console,log(rotate(data, -4)) // => [5, 1, 2, 3. 4] console,log(rotate(data, -5)) // => [1, 2, 3, 4. 5] console,log(rotate(['a', 'b', 'c']. 1)) console,log(rotate([true, true, false] 1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.