旋转数组的元素

Rotate the elements of an array

我正在尝试解决来自 jshero.net 的 javascript 挑战。挑战是这样的:

Write a function rotate that rotates the elements of an array. All elements should be moved one position to the left. The 0th element should be placed at the end of the array. The rotated array should be returned. rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].

我能想到的就是这个:

function rotate(a){
  let myPush = a.push();
  let myShift = a.shift(myPush);
  let myFinalS = [myPush, myShift]
  return myFinalS
}

但是我得到的错误信息是:

rotate(['a', 'b', 'c']) does not return [ 'b', 'c', 'a' ], but [ 3, 'a' ]. Test-Error! Correct the error and re-run the tests!

我觉得我错过了一些非常简单的东西,但我不知道是什么。你们还有其他方法可以解决这个问题吗?

function rotate(array){
   let firstElement = array.shift();
   array.push(firstElement);
   return array;
}

要实现你正在寻找的输出,首先你必须使用 Array.shift() to remove the first element, then using Array.push() 将元素添加回数组的末尾,然后 return 数组,问题是你使用了这些步骤的错误顺序,.push() 方法也将要添加的元素作为参数,这里是一个工作片段:

function rotate(a){
  let myShift = a.shift();
  a.push(myShift);
  return a;
}

console.log(rotate(['a', 'b', 'c']));

我在这里创建了一个实用程序,即使根据要求旋转数组后,输入数组也不会发生变化。

function rotate(a){
  let inputCopy = [...a]
  let myShift = inputCopy.shift();
  let myFinalS = [...inputCopy, myShift]
  return myFinalS
}

console.log(rotate([1,2,3]))
console.log(rotate(["a","b","c"]))

希望对您有所帮助。

function rotate(arr){
    let toBeLast = arr[0];
    arr.splice(0, 1);
    arr.push(toBeLast);
    return arr;
}
console.log(rotate(['a', 'b', 'c']));

堆栈溢出新手。希望这会有所帮助:)

arr.unshift(...arr.splice(arr.indexOf(k)))

使用 unshift()splice()indexOf(),这一行应该有所帮助。 arr 是您要旋转的数组,k 是您想要作为数组第一个元素的项目。函数示例可以是:

let rotate = function(k, arr) {
    arr.unshift(...arr.splice(arr.indexOf(k)))
}

这是用法示例:

let array = ['a', 'b', 'c', 'd']
let item = 'c'

rotate(item, array)
console.log(array)

// > Array ["c", "d", "a", "b"]

终于回到原来的数组:

rotate('a', array)
console.log(array)

// > Array ["a", "b", "c", "d"]