30秒学会 JavaScript 片段 · 2022年12月9日

30秒学会 JavaScript 片段 – Offset array elements

Moves the specified amount of elements to the end of the array.

  • Use Array.prototype.slice() twice to get the elements after the specified index and the elements before that.
  • Use the spread operator (...) to combine the two into one array.
  • If offset is negative, the elements will be moved from end to start.

代码实现

const offset = (arr, offset) => [...arr.slice(offset), ...arr.slice(0, offset)];

offset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]
offset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]

翻译自:https://www.30secondsofcode.org/js/s/offset-array-elements