Define an array:

var a = ["a","b","c"];Copy the code

Array detection

  • instanceof
    console.log(a instanceof Array); // trueCopy the code

Only one global scope is used in this way. If the web page contains more than one frame, error prone.

  • Array.isArray()
console.log(Array.isArray(a)); // trueCopy the code

It works regardless of how many global environments you have, but compatibility is not high.

  • Object.prototype.toString.call()
console.log(Object.prototype.toString.call(a)); // [object Array]Copy the code

Use the toString function of the object to determine compatibility. Cannot use the array’s own toString because the function has been overridden.

An array of conversion

Array to string

  • toLocaleString

    console.log(a.toLocaleString()); //a,b,cCopy the code
  • toString

    console.log(a.toString()); //a,b,cCopy the code
  • valueOf

    console.log(a.valueOf()); // Return itself ["a", "b", "c"]Copy the code
  • join

    console.log(a.join('&')); //a&b&cCopy the code

Since the first two methods become strings with “, “in the middle by default, you can change the spacer using the join method.

  • Extended operators (new in ES6)

    The extension operator is three dots (…) . It is like the inverse of the REST argument, turning an array into a comma-separated sequence of arguments.
    console.log(... [1, 2, 3)); // 1 2 3 console.log(1, ... [2, 3, 4, 5); // 1 2 3 4 5 [...document.querySelectorAll('div')]; // [<div>, <div>, <div>]Copy the code

Other data structures are converted to arrays

  • Extension operators (new in ES6) Extension operators support the conversion of data structures with iterator interfaces to arrays.
Function foo() {var args = [...arguments]; } / / NodeList object [... document querySelectorAll (' div ')]Copy the code
  • Array.from() (added in ES6)
    - Converts the data structure with the traverser interface to an array - converts the class array to an array - takes the first argument to the data structure to be converted to an array - takes the second argument to the map function, which processes the converted arrayCopy the code
  • Array.prototype.slice converts class arrays to arrays using Array methods.
  • Array.of() (new in ES6)

    Convert a set of values to an array.
    Array of (3, 11, 8) / /,11,8 [3] Array of (3) / / [3] Array) of (3). The length / / 1Copy the code

Array add and delete

The stack method

  • push

Add from the end

console.log(a.push('d')); // Return array length 4Copy the code

  • Pop is removed from the end
console.log(a.pop()); // return the removed item dCopy the code

Queue method

  • shift

Remove from head

console.log(a.shift()); // return the removed item aCopy the code

  • Unshift is added from the header
console.log(a.unshift('a')); // Return the length of the arrayCopy the code

Sort an array

  • reverse
console.log(a.reverse()); // reverse ["c", "b", "a"]Copy the code
  • sort
console.log(a.sort()); // Sort, from small to large by default, but toString is called before sortingCopy the code

You can also pass in functions:

Var values =,10,5,1,15 [0]; function compare(value1,value2) { return value1 - value2; } console.log(values.sort(compare));Copy the code

An array of operating

  • Concat Concat in-depth parsing
  • Slice Slice in-depth parsing

  • splice

Always return the deleted item, or an empty array if none is present. The first parameter indicates the starting position; The second parameter indicates the number of deletions to be made (0, no deletions). The third parameter indicates the optional item to add;

var colors1 = ["red", "green", "blue"]; The console. The log (colors1. Splice (0, 1)); //["red"] console.log(colors1); / / / "green", "blue". The console log (colors1. Splice (0, 0, "aaa")); //[] console.log(colors1); / / / "aaa", "green", "blue"] the console. The log (colors1. Splice (0, 2, "SSS")); //["aaa", "green"] console.log(colors1); //["sss", "blue"]Copy the code

  • CopyWithin () (new in ES6) Within the current array, copies the member in the specified location to another location (overwriting the original member), and returns the current array.

    Parameter list: -target (required) : Replace data from this position. - start (Optional) : reads data from this position. The default value is 0. If it is negative, it is the reciprocal. - end (Optional) : stops reading data before this position. The default value is the array length. If it is negative, it is the reciprocal.Copy the code
[1, 2, 3, 4, 5].copyWithin(0, 3); / / [4, 5, 3, 4, 5] / / copies the 3 to 0 bit [1, 2, 3, 4, 5]. CopyWithin (0, 3, 4); / / [4, 2, 3, 4, 5] / / - equivalent to the 3, 2-1 is equal to 4 [1, 2, 3, 4, 5]. CopyWithin (0, 2, 1); // [4, 2, 3, 4, 5]Copy the code
  • Fill () (new in ES6) fills an array with the given value. The first parameter indicates the value of the fill, the second parameter indicates the start of the fill, and the third parameter indicates the one before the end of the fill.
['a', 'b', 'c'].fill(7); // [7, 7, 7] new Array(3).fill(7); // [7, 7, 7] ['a', 'b', 'c'].fill(7, 1, 2); // ['a', 7, 'c']Copy the code

Find the array

  • IndexOf searches backwards and returns the position of the searched item, or -1 if none is present.

  • LastIndexOf searches backwards, returning the position of the searched item, or -1 if none is present.

  • FindIndex () (new in ES6) returns the location of the first eligible array member, or -1 if all members fail.

    [1, 5, 10, 15].findIndex(function(value, index, arr) { return value > 9; / / 2})Copy the code

The indexOf method cannot recognize NaN members of an array, but the findIndex method can do so with the object. is method.

[NaN].indexOf(NaN)
// -1
[NaN].findIndex(y => Object.is(NaN, y))
// 0Copy the code
  • Find () (new in ES6) returns the first qualified array member, or undefined if all members fail.
[1, 5, 10, 15].find(function(value, index, arr) { return value > 9; }) / / 10Copy the code
  • Includes () (new in ES6) returns a Boolean value indicating whether an array contains a given value. The first parameter indicates the value to be searched, and the second parameter indicates the starting position of the search, which defaults to 0. If the second argument is negative, it represents the reciprocal position
[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // trueCopy the code

Through the array

ES5

The first argument passed in is a function that takes three arguments, item, index, and array

  • Every queries whether each item meets the requirements
  • Filter Filter the items that meet requirements
  • ForEach does something and returns no value
  • Map does something and returns
  • Some has one item that meets the requirements

ES6 new

They both return a traverser object, which can be used for… The of loop is traversed, the only differences being that keys() is traversal of key names, values() is traversal of key values, and entries() is traversal of key value pairs.

  • entries()
  • keys()
  • values()
for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1
for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'
for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"Copy the code

You can also call the next() method manually.

let letter = ['a', 'b', 'c'];
let entries = letter.entries();
console.log(entries.next().value); // [0, 'a']
console.log(entries.next().value); // [1, 'b']
console.log(entries.next().value); // [2, 'c']Copy the code

Merge method

  • reduce

    Forward-backward iteration

    The first argument is a function (the arguments are the previous value, the current value, the index, the array), and the second item is iterated over. The preV of each iteration is the result of the previous iteration.
    Var values = [1, 2, 3, 4, 5]; var sum = values.reduce(function (prev, cur, index, array) { return prev * cur; }); console.log(sum); / / 120 1 * 2 * 3 * 4 * 5Copy the code

The second parameter is the starting value.

Var values = [1, 2, 3, 4, 5]; var sum = values.reduce(function (prev, cur, index, array) { return prev * cur; }, 2); console.log(sum); / / 240 2 * 1 * 2 * 3 * 4 * 5Copy the code
  • ReduceRight iterates back to front