Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities

preface

Today I met a handwritten question, as follows:

// JS- Array element position loop left and right

function move(arr, n) {

  // TODO

}
var arr = [0.1.2.3.4.5];
console.log(move(arr, -2)); // [1, 2, 3, 4, 5, 0]
console.log(move(arr, -1)); // [2, 3, 4, 5, 0, 1]
console.log(move(arr, 1)); // [5, 0, 1, 2, 3, 4]
console.log(move(arr, 2)); // [4, 5, 0, 1, 2, 3]
console.log(move(arr, 3)); // [3, 4, 5, 0, 1, 2]
Copy the code

Slice, splice, Pop, Shift… And then try, and finally

function move(arr, n) {
  let newArr = [
    ...arr.slice(-n, arr.length),
    ...arr.slice(0, n > 0 ? arr.length - n : -n),
  ];
  return newArr;
}
Copy the code

Be solved. Took a quick look at Slice’s MDN

The slice method can be used to convert an array-like object/collection into a new Array

And this operation? So how do we create arrays in general?

Constructor creation

new Array(3)
Copy the code

Array literals created

const names = ['Grey'.'Shelly'.'John']
Copy the code

Note that, as with objects, the Array constructor is not called when an Array is created using Array literal notation

Static method creation

There are two ways to do this

  • Array.from()

Creates a new, shallow-copy array instance from an array-like or iterable.

// The existing array can be enhanced when the second argument is entered
Array.from({length: 5}, (v, i) = > i);
// [0, 1, 2, 3, 4]
Copy the code
  • Array.of()

Creates a new array instance with a variable number of arguments, regardless of the number or type of arguments.

Its compatibility stands out in the context column:

if (!Array.of) {
  Array.of = function() {
    return Array.prototype.slice.call(arguments);
  };
}
Copy the code

This turns out to be an alternate to one of the uses of slice.