将数组的前三个元素移到最后的最佳方法是什么?

时间:2016-07-14 07:32:50

标签: arrays

我有阵列[" a"," b"," c"," d"," e&# 34] 我需要一个函数将abc转换到数组的末尾 - [" d"," e"," a"," b" ," c"]

1 个答案:

答案 0 :(得分:4)

function rotate(a, n) {
  // The modulo here is a performance optimization... rotating by the length of the array has no effect. E.g. in this example, rotating 8 is the same as rotating 3.
  for (var i = 0; i < n % a.length; i++) {
    a.push(a.shift());
  }
}

var a = ["a", "b", "c", "d", "e"];

rotate(a, 3);

console.log(a);

// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]

修改

使用slice的非破坏性版本:

function rotate(a, n) {
  n %= a.length;
  return a.slice(n).concat(a.slice(0, n));
}

var a = ["a", "b", "c", "d", "e"];

console.log(rotate(a, 3));

// Output:
// [ 'd', 'e', 'a', 'b', 'c' ]

<强> EDIT2

在回复评论中的后续问题时,请按照以下方式复制元素而不是移动它们。 (这是非破坏性版本。)

function copy(a, n) {
  n %= a.length;
  return a.concat(a.slice(0, n));
}

var a = ["a", "b", "c", "d", "e"];

console.log(copy(a, 3));

// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]

或者这里是copy的就地版本:

function copy(a, n) {
  for (var i = 0; i < n % a.length; i++) {
    a.push(a[i]);
  }
}

var a = ["a", "b", "c", "d", "e"];

copy(a, 3);

console.log(a);

// Output:
// [ 'a', 'b', 'c', 'd', 'e', 'a', 'b', 'c' ]