Abstract: How good it is to use native methods.

  • 9012, Array Array method quickly use!
  • Author: Twenty two

FundebugReproduced with authorization, copyright belongs to the original author.

preface

Writing business code for a long time, I have to be abandoned by the society. Today, when I went back to consolidate the basic knowledge, I found that THERE are many methods that I do not often use in my business, or I do not know that method, so I rewrite a method to achieve it. Do you use only concat, Join, POP, push, Shift, unshift, reverse, sort, slice, splice, toString, indexOf, find, etc., for Array objects? Let’s take a look at some of the Array object methods we use less or less!

1. Array.from()

Creates a new array instance from an array-like or iterable

1.1 grammar

/** * @description - Creates a new instance of an array from an array-like or iterable (pseudo-array object: any object with a length attribute and index attributes; Iterable: can get the elements of an object, such as a Map and a Set, etc.) * @param arrayLike - A pseudo-array object or iterable that you want to convert to an array. * @param thisArg - This object is optional when mapFn is called. * @return {Array} - a new Array instance */
Array.from(arrayLike[, mapFn[, thisArg]])
Copy the code

1.2 the sample

// Array from a String
Array.from('foo');
// ["f", "o", "o"]

// Array from a Set
let s = new Set(['foo'.window]);
Array.from(s)
// ["foo", window]

// Array from a Map
let m = new Map([[1.2], [2.4], [4.8]]);
Array.from(m);
// [[1, 2], [2, 4], [4, 8]]

// Array from an Array-like object (arguments)
function f() {
  return Array.from(arguments);
}
f(1.2.3);
/ / [1, 2, 3]

// Use the arrow function in array. from
Array.from([1.2.3], x => x + x);
/ / (2, 4, 6]

/ / false array
Array.from({length: 5});
// [undefined, undefined, undefined, undefined, undefined]
Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

// Change this object when the callback function mapFn is changed
Array.from({[1.2.3].function(){console.log(this)});
// In the browser environment, the Window object is three times

var obj ={name: 'obj'}
Array.from({[1.2.3].function(){console.log(this)}, obj);
// obj object three times
Copy the code

2. Array.prototype.copyWithin()

Shallowly copies part of an array to another location in the same array and returns it without changing the length of the original array.

2.1 grammar

/** * @description - Shallowly copies part of the array to another location in the same array and returns it without changing the length of the original array. * @param target-0 is the base index and copies the sequence to that location. If target is after start, the copied sequence is modified to match the index based on arr.length. * @param start-0 to start copying the starting position of the element. If it is negative, start is evaluated from the end. If start is ignored, copyWithin will start copying from 0. * @param end-0 is the base index that starts copying the end of the element. CopyWithin will be copied to that location, but not to the end element. If it is negative, end is evaluated from the end. * @return {array} - Changed array */
arr.copyWithin(target[, start[, end]])
Copy the code

2.2 the sample

let numbers = [1.2.3.4.5];

numbers.copyWithin(2 -);
// [1, 2, 3, 1, 2]

numbers.copyWithin(0.3);
// [4, 5, 3, 4, 5]

numbers.copyWithin(0.3.4);
// [4, 2, 3, 4, 5]

numbers.copyWithin(2 -.- 3.- 1);
// [1, 2, 3, 3, 4]

[].copyWithin.call({ length: 5.3: 1 }, 0.3);
// {0: 1, 3: 1, length: 5}

// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1.2.3.4.5]);

i32a.copyWithin(0.2);
// Int32Array [3, 4, 5, 4, 5]

// On platforms that are not yet ES2015 compliant:
[].copyWithin.call(new Int32Array([1.2.3.4.5]), 0.3.4);
// Int32Array [4, 2, 3, 4, 5]
Copy the code

3. Array.prototype.some()

Tests whether at least one element passes the test implemented by the provided function.

3.1 grammar

/** * @description - Tests whether at least one element of the array passes the test of the specified function. * @param callback - A function used to test each element. * @param thisArg - This value used when executing callback. * @return {Boolean} - Whether the test passes. * /
arr.every(callback[, thisArg])
Copy the code

3.2 the sample

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

4. Array.prototype.every()

Tests whether all elements of the array pass the test for the specified function.

4.1 grammar

/** * @description - Tests whether all elements of the array pass the test of the specified function. * @param callback - A function used to test each element. * @param thisArg - This value used when executing callback. * @return {Boolean} - Whether the test passes. * /
arr.every(callback[, thisArg])
Copy the code

4.2 the sample

function isBigEnough(element, index, array) {
    return element >= 10;
}
var passed = [12.5.8.130.44].every(isBigEnough);
// passed is false
passed = [12.54.18.130.44].every(isBigEnough);
// passed is true
Copy the code

5. Array.prototype.flat()

The array is recursively traversed at a specified depth, and all elements are merged with the elements in the traversed subarray into a new array.

5.1 grammar

/** * @description - Recursively iterates through the array at a specified depth, and returns a new array that combines all elements with the elements in the traversed subarray. * @param depth - Specifies the structure depth to extract the nested array. The default value is 1. * @return {array} - a new array containing all the elements of the array and its subarrays. * /
arr.flat(depth);

Copy the code

5.2 the sample

var arr1 = [1.2[3.4]];
arr1.flat();
// [1, 2, 3, 4]

var arr2 = [1.2[3.4[5.6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1.2[3.4[5.6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

// Use Infinity as the depth to expand a nested array of any depth
arr3.flat(Infinity);
// [1, 2, 3, 4, 5, 6]

// Removes an empty item from the array
var arr4 = [1.2.4.5];
arr4.flat();
// [1, 2, 4, 5]

Copy the code

6. Array.prototype.flatMap()

Each element is mapped using a mapping function, and the result is compressed into a new array. It is almost identical to a map and a flat with a depth value of 1, but flatmaps are usually slightly more efficient when combined into one method.

6.1 grammar

/** * @description - Maps each element using the mapping function and compresses the result into a new array. * @param callback - a function that generates an element in a new array, passing in three arguments: * @param currentValue - The element currently being processed in the array. * @param index - Optional. The index of the current element being processed in the array. * @param array - Optional. The map array to be called. * @param thisArg - Optional. The this value used when the callback function is executed. * @return {array} - A new array where each element is the result of a callback function and the structure depth is 1. * /
arr.flatMap(function callback(currentValue[, index[, array]]) {
    // Returns the elements of the new array
}[, thisArg])

Copy the code

6.2 the sample

let arr = ["It's a nice day.".""."Good morning."];

arr.map(s= > s.split(""));
/ / [[" today ", "day", "day", "gas", "no" and "wrong"], ["], [" early ", "on", "good"]]

arr.flatMap(s= > s.split(""));
/ / / "today", "day", "day", "gas", "no" and "wrong", ""," early ", "on", "good"]

Copy the code

7. Array.prototype.includes()

Used to determine whether an array contains a specified value, returning true if it does, false otherwise.

Note: Object arrays cannot be checked using the includes method.

7.1 grammar

/** * @description - Determines whether an array contains a specified value. * @param valueToFind - The element value to look for. * @param fromIndex - Optional. Start looking for valueToFind at the fromIndex index. If it is negative, the search starts in ascending order from array.length + fromIndex's index (even if you skip the fromIndex absolute index from the end and then search backwards). The default is 0. * @return {Boolean} - Whether to include * /
arr.includes(valueToFind[, fromIndex])

Copy the code

7.2 the sample

[1.2.3].includes(2); // true
[1.2.3].includes(4); // false
[1.2.3].includes(3.3); // false
[1.2.3].includes(3.- 1); // true
[1.2.NaN].includes(NaN); // true

Copy the code

8. Array.prototype.lastIndexOf()

Returns the index of the last element in the array for the specified element (that is, a valid JavaScript value or variable), or -1 if none exists. Look forward from the back of the array, starting at fromIndex.

8.1 grammar

/** * @description - Returns the index of the last element in the array. * @param searchElement - The element to be searched. * @param fromIndex - Optional. Start looking backwards from this location. * @return {Boolean} - Whether to include * /
arr.lastIndexOf(searchElement[, fromIndex = arr.length - 1])

Copy the code

8.2 the sample

var array = [2.5.9.2];
var index = array.lastIndexOf(2);
// index is 3
index = array.lastIndexOf(7);
// index is -1
index = array.lastIndexOf(2.3);
// index is 3
index = array.lastIndexOf(2.2);
// index is 0
index = array.lastIndexOf(2.2 -);
// index is 0
index = array.lastIndexOf(2.- 1);
// index is 3

Copy the code

9. Array.prototype.reduce()

Execute a Reducer function (in ascending order) that you provide on each element in the array and summarize its results into a single return value.

9.1 grammar

/** * @description - Execute a ** Reducer ** function provided by you (in ascending order) on each element in the array and summarize its results into a single return value. * @param callback - A function that executes each value in the array and contains four arguments: * @param accumulator - the value returned by the accumulator callback; It is the cumulative value, or initialValue, returned when the callback was last called. * @param currentValue - The element currently being processed in the array. * @param index - Optional. The index of the current element being processed in the array. * @param array - Optional. The map array to be called. * @param initialValue - Optional. As the value of the first argument when the callback function is first called. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error. * @return - Cumulative processing result of the function. * /
arr.reduce(callback[, initialValue])

Copy the code

9.2 the sample

// The maximum value in the array
var arr = [10.0.100.99.48.101];
var reducer = (x, y) = > Math.max(x, y);
arr.reduce(reducer); / / 101

/ / accumulation
var reducer2 = (x, y) = > x + y;
arr.reduce(reducer2); / / 358

Copy the code

10. Array.prototype.entries()

Returns a new Array Iterator containing key/value pairs for each index in the Array.

10.1 grammar

/** * @description - Returns a new Array Iterator containing key/value pairs for each index in the Array. * @return {Array Iterator} - a new Array Iterator object. * /
arr.entries();

Copy the code

10.2 the sample

var arr = ["a"."b"."c"];
var iterator = arr.entries();
console.log(iterator);
/* Array Iterator {} __proto__:Array Iterator next:ƒ next() Symbol(symbol.tostringtag):"Array Iterator" __proto__:Object * /

for (let e of iterator) {
    console.log(e);
}

// [0, "a"]
// [1, "b"]
// [2, "c"]

Copy the code

Note: most of the above are in the document, but personal use notes rarely or unused, and then make a unified record. It looks like they’re all ES6’s, 9012 years old, so use them! That means copying the document, big guy light spray!

Small AD

My own operation of the public number, record my own growth!

Public account: Front-end day

Official ID: Js-say