Extension of the array ES6 study notes

✏️1. Extended operator

Extended operator (Spread) is three dots ( ...), the array into a sequence of parameters separated by commas.

  • Common usage
console.log(...[1,2,3]);//1 2 3
  • Array copy (deep copy common type, complex type shallow copy)
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [...arr1];
arr2[0] = 666;
console.log('arr2:', arr2);//[666,2,3,4,5]
console.log('arr1:', arr1);//[1,2,3,4,5]
  • Striped array (destructuring assignment)
const arr1=[1,'2','3','4'];
const [,...arr2]=arr1;
console.log('arr2 :', arr2);//arr2 : ["2", "3", "4"]
  • Array merge
let arr1=[1,2,3],
arr2=[4,5,6];
let arr3=[...arr1,...arr2];//[1,2,3,4,5,6]
  • Passing parameters
function add(x,y) {
    return x+y;
}
const arr=[1,2];
console.log(add(...arr));//3
  • Alternative methods apply function
// ES5 的写法
function f(x, y, z) {
  // ...
}
var args = [0, 1, 2];
f.apply(null, args);

// ES6的写法
function f(x, y, z) {
  // ...
}
let args = [0, 1, 2];
f(...args);
// ES5 的写法
Math.max.apply(null, [14, 3, 77])//77

// ES6 的写法
Math.max(...[14, 3, 77])//77

// 等价于
Math.max(14, 3, 77);//77
  • Turn an array of strings
[..."abcdefg"];//[a,b,c,d,e,f,g]

✏️2. Extended example method

1.Array.from

The category array into an array (with the length property ①, ② can be traversed)

Convert custom objects

let arrayLike = {
    '0': 'a',
    '1': 'b',
    '2': 'c',
    length: 3
};

// ES5的写法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']

// ES6的写法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']

Turn an array of strings

Array.from('hello')

Set switch array

    let set=new Set(['name','age']);
    console.log(Array.from(set));//["name", "age"]

Array.from can also accept a second parameter, the method acts like map array, each element to be processed, the value of the processed returned into the array.

Array.from(arrayLike, x => x * x);
// 等同于
Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)

2.Array.fill()

fill using the given value, a filled array.

{
    // 1参数
    const arr1 = [1, 2, 3, 4, 5];
    let arr2 = [...arr1].fill(3);

    // 三参数:用6从下标0开始填充直到下标3之前
    console.log(arr2);//333333
    console.log([...arr1].fill(6, 0, 3))//66645

    const arr3 = [];
    console.log(arr3.fill(0, 0, 10));//[]

    // 初始化数组
    let arr=new Array(5).fill(0);
    console.log(arr);//[0,0,0,0,0]
}

3.Array.find(),Array.findIndex

Find array instance method for finding the first qualifying array members. Its argument is a callback function, all members of the array in order to execute the callback function until you find the first member of a return value of true, then returned to the members. If there are no qualified members, returns undefined.

findIndex array instance method of usage and find methods are similar, returns the first member of the array in line with the conditions of the location, if all the members are not eligible, -1 is returned.

  • Find the first member of an array of greater than 5
let arr=[1,3,4,2,8,4,8];
let res=arr.find(v=>{
    return v>5;
})
let resIndex=arr.findIndex(v=>{
    return v>5;
})
console.log(res,resIndex);//8 4
  • find, there are three methods findIndex callback parameters, followed by the current value, the current location, the original array
let res=[1,2,3,4,5].find((v,i,arr)=>{
    return arr[i]===v;
})
console.log(res);//1

4.Array.includes() 和 Array.indexOf()

Array.prototype.includes method returns a Boolean value indicating whether the array contains a given value, the method includes similar string. ES2016 introduced this method.

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false

The second parameter indicates the start of the search process, the default is 0. If the second parameter is negative, then the reciprocal position, if it is greater than the time length of the array (such as a second argument -4, but the length of the array 3), is reset to 0 from the start.

[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

Before determining whether to include a target value indexOf, indexOf method has two disadvantages, 1. Semantic enough, its meaning is to find the first occurrence of the parameter value of position, so go to whether the comparison is not equal to -1, it Expression not intuitive. 2. It is exactly equal internal operator (===) for determination, which results in misjudgment for a NaN.

[NaN].indexOf(NaN)//-1
[NaN].includes(NaN)//true

5.Array.flat()

Sometimes members of the array or array, Array.prototype.flat () is used to expand the nested arrays into one-dimensional array. The method returns a new array without affecting the original data.

[1,2,[3,4],5,[6]].flat();
// [1, 2, 3, 4, 5, 6]

Flat () expand only one default, if you want to expand the multilayer nested array, the parameters can be Flat () method write an integer representing the number of layers desired deployment, the default is one.

[1, 2, [3, [4, 5]]].flat()
// [1, 2, 3, [4, 5]]

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

If no matter how many layers of nested, should turn into a one-dimensional array can be used as an argument Infinity keywords.

[1, [2, [3]]].flat(Infinity)
// [1, 2, 3]

If available, automatically skips vacancy

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

Guess you like

Origin www.cnblogs.com/roseAT/p/11464924.html