Array methods provided in ECMAScript 5.1

Some of these methods, ECMAScript 3, appear, but are not broken down in this article.

ECMA – 262/5.1 specification

Check if it’s an array

Array.isArray ( arg )
// false or true
Copy the code

IE9- browsers that do not support this method can handle this:

Object.prototype.toString.call(obj) === '[object Array]';
Copy the code

Conversion method

toString

ValueOf of arrays calls toString by default, so they all return the same comma-separated string of each item

var months = ['Jan', 'Feb', 'Mar', 'Apr'];
months.toString(); // "Jan,Feb,Mar,Apr"
Copy the code

toLocaleString

Calling the toLocaleString method on each item of the array sometimes gives the same result as the toString method. Sometimes, for example, an array of the elements of the Date object returns a different result.

join

a.join();      // 'Wind,Rain,Fire'
a.join(', ');  // 'Wind, Rain, Fire'
a.join(' + '); // 'Wind + Rain + Fire'
a.join('');    // 'WindRainFire'
Copy the code

If the valueOf an item in the array is null or undefined, the value is represented as an empty String in the result returned by the join(), tolocale-string (), toString(), and valueOf() methods

The reverse method is string.split ()

The stack method

Pop deletes the last item of the array

Operates on the original array to return the deleted item

var a = [1, 2, 3]; var b = a.pop(); console.log(a); // [1, 2] console.log(b); / / 3Copy the code

Push adds a new element to the end of the array

Operation on the original array, returns the array length

var a = [1, 2, 3]; var b = a.push(4, 5); console.log(a); // [1, 2, 3, 4, 5] console.log(b); / / 5Copy the code

Queue method

Shift deletes the first item in the array

Operation to return the deleted item

var a = [1, 2, 3]; var b = a.shift(); console.log(a); // [2, 3] console.log(b); / / 1Copy the code

Adds a new element to the front of the unshift array

Operation on the original array, returns the array length

var a = [1, 2, 3]; var b = a.unshift(4, 5); console.log(a); // [4, 5, 1, 2, 3] console.log(b); / / 5Copy the code

Reorder method

Reverse Reverses the order of the array items

Operates on the original array and returns the array

var a = ['one', 'two', 'three'];
var b= a.reverse();

console.log(a); // ['three', 'two', 'one']
console.log(b); // ['three', 'two', 'one']
Copy the code

The sort order

Sort by Unicode code position, ascending by default

var fruit = ['cherries', 'apples', 'bananas']; fruit.sort(); // ['apples', 'bananas', 'cherries'] var scores = [1, 10, 21, 2]; scores.sort(); / / [1, 10, 2, 21] // because '10' is mix of two characters '1' and '0' so '10' is before '2' in Unicode code point order.Copy the code

Undefined will be put at the end of the array

I wrote an in-depth explanation of the sorting method before, if you are interested, click here

JavaScript array.prototype.sort

Operation method

Concat merges arrays

Return a new array

var arr1 = ['a', 'b', 'c']; var arr2 = ['d', 'e', 'f']; var arr3 = arr1.concat(arr2); console.log(arr3); // expected output: ["a", "b", "c", "d", "e", "f"] var arr4 = arr1.concat(1, [4, [5, 6]]); console.log(arr4); // Guess the result of this? / / output: [' a ', 'b', 'c', 1, 4, [5, 6]] / / if the incoming is an array, is its value. But arrays of arrays are reserved.Copy the code

Slice creates a new array based on the current array

Return a new array

We pass in two arguments: the start position (included) and the end position (not included).

You just pass one argument and by default it’s cut to the end of the array, which is considered the starting position

If one of the arguments passed is negative, the position is determined by adding the number to the array length. An array of length 5 slice (-2, -1) has the same result as slice (3, 4).

An empty array is returned if the end position is less than the start position

var a = ['1', '2', '3', '4']; var sliced = a.slice(1, 3); console.log(a); // ['1', '2', '3', '4'] console.log(sliced); / / / '2', '3'Copy the code

splice

You can delete, insert (the number of elements is greater than the number of elements to delete), replace (delete one, add another)

Returns an array of deleted elements, or an empty array if none were deleted

Parameters: starting position (inclusive), number of elements to delete, element

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum');
// ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1);
// ["angel", "clown", "mandarin", "sturgeon"]

myFish.splice(-1, 0, 'drum');
//["angel", "clown", "mandarin", "drum", "sturgeon"]
Copy the code

It’s different from concat if you insert an array, you insert an array, you don’t unpack the array.

myFish.splice(2, 1, ["hello", "world"]);
// ["angel", "clown", ["hello", "world"], "sturgeon"]
Copy the code

Location method

Both indexOf and lastIndexOf take two arguments: the value to be searched and the start of the search

Does not exist, return -1; Yes, return to position. IndexOf is looking backwards, lastIndexOf is looking backwards.

indexOf

var a = [2, 9, 9];
a.indexOf(2); // 0
a.indexOf(7); // -1

if (a.indexOf(7) === -1) {
  // element doesn't exist in array
}
Copy the code

lastIndexOf

var numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); // -1 numbers.lastIndexOf(2, 3); // 3 numbers.lastIndexOf(2, 2); // 0 numbers.lastIndexOf(2, -2); // 0 numbers.lastIndexOf(2, -1); / / 3Copy the code

An iterative approach

ECMAScript 5 provides five iterative methods, all of which take arguments

Given function (current element, position, array)

Optionally, the callback is performed with this value

every

Returns true if the given function is run on each item of the array and returns true on each item

function isBigEnough(element, index, array) {
  return element < 10;
}

[2, 5, 8, 3, 4].every(isBigEnough);   // true
Copy the code

some

Returns true if the given function is run on each item of the array and returns true on any of the items

function isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true
Copy the code

filter

The given function is run on each item of the array, returning an array of items whose result is true

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];

var longWords = words.filter(function(word){
  return word.length > 6;
});
// Filtered array longWords is ["exuberant", "destruction", "present"]
Copy the code

map

The given function is run on each item of the array, returning the result of each function call to form a new array

var numbers = [1, 5, 10, 15];
var doubles = numbers.map(function(x) {
   return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
Copy the code

ForEach array traversal

const items = ['item1', 'item2', 'item3'];
const copy = [];

items.forEach(function(item){
  copy.push(item)
});
Copy the code

Narrow method

Reduce and reduceRight are traversed from front to back, and the other is traversed from back to front, which has one more parameter than the callback function of the above five iterative methods: the value of the previous item

Callback function argument, current element, position, array

reduce

var numbers = [0, 1, 2, 3];

var result = numbers.reduce(function(accumulator, currentValue) {
    return accumulator + currentValue;
});

console.log(result);
// expected output: 6
Copy the code

reduceRight

var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { return a.concat(b); } []); // flattened is [4, 5, 2, 3, 0, 1]Copy the code

A small summary

The queue method and stack method operate on the original array. When adding an array element, the return value is the array length. When an array element is deleted, the return value is the deleted element.

Which methods change the original array?

Stack methods: push, pop

Queue methods: shift, unshift

Reorder methods: reverse, sort

Which methods return arrays?

Reorder methods: reverse, sort

Operation methods: splice, slice, concat

In the iterative method: filter, map

New methods in ECMAScript 6.0

ECMA – 262/6.0 specification

from

Convert array-like objects and iterable objects into true arrays

const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]

Array.from('foo');
// ["f", "o", "o"]
Copy the code

of

Used to convert a set of values into an array

The main purpose of this method is to complement the Array constructor Array(). Array() behaves differently because of the number of arguments.

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]
Copy the code
Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // [ , , , , , , ] Array(1, 2, 3); / / [1, 2, 3]Copy the code

copyWithin

Copies the element at the specified location to another location (overwriting the original element), returning the current array. This method modifies the current array.

It takes three arguments.

  • Target (required) : Replace data from this location.
  • 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 until this position, which is equal to the array length by default. If it is negative, it is the reciprocal.
[1, 2, 3, 4, 5].copyWithin(-2);
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]
Copy the code

fill

Fills an array with the given value.

Erases the original elements of the group

You can also accept the second and third parameters that specify the start and end positions of the fill.

var numbers = [1, 2, 3]
numbers.fill(1);
// results in [1, 1, 1]

['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
Copy the code

find

Find the first array element that meets the criteria. The argument is a callback function that is executed by all array elements until it finds the first element that returns true, and returns that element. If there is no qualified element, undefined is returned. The callback can take three arguments, the current value, the current position, and the original array.

[1, 5, 10, 15].find(function(value, index, arr) {
  return value > 9;
}) // 10

[1, 5, 2, 3].find(function(value, index, arr) {
  return value > 9;
}) // undefined
Copy the code

findIndex

The findIndex method is used very much like the find method, returning the location of the first qualifying array element, or -1 if all elements fail.

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

ES6 provides three new methods — entries(), keys() and values() — for traversing groups of numbers. 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.

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

entries

var a = ['a', 'b', 'c'];
var iterator = a.entries();

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

keys

var arr = ['a', 'b', 'c'];
var iterator = arr.keys();

console.log(iterator.next()); // { value: 0, done: false }
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Copy the code

values

var a = ['w', 'y', 'k', 'o', 'p'];
var iterator = a.values();

console.log(iterator.next().value); // w
console.log(iterator.next().value); // y
console.log(iterator.next().value); // k
console.log(iterator.next().value); // o
console.log(iterator.next().value); // p
Copy the code

For more information about how to use ECMAScript, see Ruan Yifeng’s Introduction

Methods added to ECMAScript 7.0

ECMA – 262/7.0 specification

includes

Determines whether the element exists in the array

Parameters: the value to be searched and the starting position

IndexOf can be replaced in ES5 era

IndexOf determines whether an element is a NaN, which is incorrect

var a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false
Copy the code

ECMA – 262/8.0 specification

ES8 does not add array methods

reference

JavaScript advanced programming

MDN web docs

Getting started with ECMAScript 6