ES6 数组的拓展(五)

一、扩展运算符(...)
将数组转化为以,分割的字符串
eg:

    console.log(...[1,2,3,4]);    //1 2 3 4 

将字符串转化为数组
eg:

    console.log([...'hello']);  //['h','e','l','l','o']

求数组中最大值
eg:

    //求参数中最大值
    let result1 =  Math.max(2,5,8,23,75);
    console.log(result1);
    //ES5中求数组中的最大值
    let result2 =  Math.max.apply(null,[2,5,8,23,75]);
    console.log(result2);    //75
    //ES6中求数组中的最大值
    let result3 =  Math.max(...[1,2,3,4,5,6,7]);
    console.log(result3);    //7


二、数组新添方法
具备Iterator接口的数据结构:Array、String、类数组对象、Set和Map集合、

Array.from()    【将具备Iterator接口的数据结构转化为数组,并返回该数组

Array.of()      【返回参数值组成的数组
弥补构造函数创建数组的不足
eg:

    let arr1 = new Array(10);  //创建一个长度为10的空数组arr1
    let arr2 = Array.of(10);    //创建数组arr2 = [10];

   
find()和findIndex()    
find()    【返回第一个符合条件的数组元素或undefined
findIndex()    【返回第一个符合条件的数组元素的索引或-1
eg:

    let arr = [16,17,14,19,20,14,30]
    //返回第一个符合条件的数组元素或undefined
    let result = arr.find((element,index,arr)=>{
        return element>18;
    });
    console.log(result);    //19

    //返回第一个符合条件的数组元素的索引或-1
    let result2 = arr.findIndex((element,index,arr)=>{
        return element>18;
    });
    console.log(result2);    //3


fill()    【使用给定参数值作为单个元素值替换数组中的所有元素
eg:

    [1,2,3].fill('hello');  //返回结果为:['hello','hello','hello']

   
arr.keys()    【返回包含所有元素索引的迭代器数组对象

arr.values()    【返回包含所有元素值的迭代器数组对象

arr.entries()返回数组中元素索引、元素值以key-value形式的组成的迭代器数组对象】[[index1,element1],[index2,element2]]
注:
    迭代器对象可以使用for-of来遍历获取里面的值
eg:

    for(let [index,element] of arr.entries()){
        console.log(index,element);    //index为arr的元素索引,element为对应的索引的元素值
    }

   
includes()    【判断数组中是否包含参数中的值,返回boolean类型
eg:

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


   

posted @ 2019-08-15 22:13  nzc  阅读(177)  评论(0编辑  收藏  举报