ES6 新增特性总结

194 阅读6分钟

1.数组

1.Array.of() // 创建数组,将参数中的值作为元素形成数组
eg:
    let str ='1,2,3'
    Array.of(str) // [1,2,3]
   
注:参数可以为任意类型,参数为空,则返回空数组 []

2.Array.from() // 将一个类数组对象或者可遍历对象转换成一个真正的数组
eg:
    a.类数组转换成真正的数组 (必须有length属性且属性名为数字,或字符串类型的数字)
        let obj = {
            0:'tom', // '0':'tom' (√)   'a':'tom' (×) 得到的是undefined
            1:'65',
            2:'男',
            3:['jane','john','Mary'],
            'length':4 // 如果没有定义 length,则返回空数组[]
        }
        Array.from(obj) // ["tom", "65", "男", Array(3)]

        注:
            1.如果没有length属性,则返回空数组[]
            2.如果对象的属性名不是数字类型,则返回对应长度为length的[undefined, undefined,undefined,undefined]数组
        
    b.将Set结构的数据转换为真正的数组
        let arr3 = new Set([4,5,6])
        Array.from(arr3) // [4,5,6]
        
    c.接受第二参数,作用类似于数组map方法,对每个元素处理,返回新的数组
        let arr5 = Array.from(arr4,item=>item*2) // [8,10,12]
    
    d:将字符串转换成数组:
        let str2 = 'hello'
        Array.from(str2) // ["h", "e", "l", "l", "o"]
    
    e:参数是一个数组:则返回一个一样的数组 或者参数含空位
        let arr7 = [1,2,3]
        let arr8 = [1,,2,3]
        Array.from(arr7) // [1,2,3]
        Array.from(arr8) // [1,undefined,2,3]
        
    f:转换map结构 (键值对形式的数据结构 key 可以是任意类型)
        let map = new Map()
        map.set('name','小红')
        map.set(true,'男')
        console.log(map) // {"name" => "小红", true => "男"}
        Array.from(map) // [["name", "小红"],[true, "男"]]
        
4.Array.filter() // 数组过滤
let a = [    {name: 'kele',title: '可口可乐'},    {name: 'kele', title: '芬达'},    {name: 'wlg',title: '王老吉'}]
let b = a.filter(item => item.name === 'kele');
console.log(b) //[{name: 'kele', title: '可口可乐'},{name: 'kele', title: '芬达'}]
5.Array.every() // 判断数组中所有的元素都符合条件时,返回true 可以理解为且的关系
let a = [1,2,3,4,5];
let b = a.every(item => item > 2);
console.log(b) // false
6.Array.some() // 判断数组中有一个元素符合条件,就返回true 可以理解为或的关系
let a = [1,2,3,4,5];
let b = a.some(item => item > 2);
console.log(b) // true
7.Array.find() // 返回数组中符合条件的第一个元素,否则就返回undefined
let a = [1,2,3,4,5]
let b = a.find(item => item > 2)
console.log(b) // 3
8.Array.findIndex() // 返回数组中符合条件的第一个元素的索引值,否则就返回-1
let a = [1,2,3,4,5]
let b = a.findIndex(item => item > 2)
console.log(b) // 2
9.Array.includes(val,index) // 判断数组中是否包含有指定的值,包含就返回true,否则就是false 等同于indexof ,第一个参数必填,搜索的值,第二参数是搜索开始的位置
let a = [1,2,3,4,5]
let b = a.includes(2)
console.log(b) // true
9.Array.map(callback) // 返回一个根据你callback函数中的条件,返回一个全新的数组
let a = [1,2,3,4,5]
let b = a.map(item => item*2)
console.log(b) // [2,4,6,8,10]  返回一个全新的数组
10.Array.reduce(callback) // 根据callback中的条件对数组中的每个元素都进行类加的操作,返回一个全新的值
let a = [1,2,3,4,5]
let b = a.reduce((pre,cur)=>{return pre+cur})
console.log(b) // 15  求和操作
11.合并数组---运算扩展符
let a = [1,2,3]
let b = [4,5,6]
let c = [...a,...b]
12.新增数组扩展:
a:多维数组的扁平化 

    方法1:arr.flat(depth)  // depth:展开嵌套数组的深度 默认1 depth = Infinity 表示无论多少层都转化成一维
        let a = [1,2,[3,5,[678,[4,8,9]]]]
        let b = a.flat(3) // [1,2,3,5,678,4,8,9]
        
    方法2:利用 reduce 函数迭代
        var arr = [1,[2,[3,[4,5],6]]];
        function flatten (arr) {
            return arr.reduce((pre, item) => Array.isArray(item) ? pre.concat(flatten(item)) : pre.concat(item) , [])
        }
        console.log(flatten(arr));  //[1, 2, 3, 4, 5, 6]
   方法3:扩展运算符
  function flatten(arr) {
      while (arr.some((item) => Array.isArray(item))) {
        arr = [].concat(...arr)
      }
      return arr
   }

    let arr = [1, 2, [3, 4], [5, [6, 7]]]
    console.log(flatten(arr))

        
b:数组循环的比较:
    1.for ,forEach, for ..of 3者的区别:
        三者都是基本的由左到右遍历数组
        forEach 无法跳出循环;forfor ..of 可以使用 break 或者 continue 跳过或中断。
        for ...of 直接访问的是实际元素。for 遍历数组索引,forEach 回调函数参数更丰富,元素、索引、原数组都可以获取。
        for ...offor 如果数组中存在空元素,同样会执行。
        
   2.some、every区别: 
        二者都是用来做数组条件判断的,都是返回一个布尔值
        二者都可以被中断
        some 若某一元素满足条件,返回 true,循环中断;所有元素不满足条件,返回 false。
        every 与 some 相反,若有益元素不满足条件,返回 false,循环中断;所有元素满足条件,返回 true3.filter、map 区别:
        二者都是生成一个新数组,都不会改变原数组(不包括遍历对象数组是,在回调函数中操作元素对象)
        二者都会跳过空元素
        map 会将回调函数的返回值组成一个新数组,数组长度与原数组一致。
        filter 会将符合回调函数条件的元素组成一个新数组,数组长度与原数组不同。
        map 生成的新数组元素是可自定义。
        filter 生成的新数组元素不可自定义,与对应原数组元素一致。
        
4.find、findIndex区别:
    二者都是用来查找数组元素。
    find 方法返回数组中满足 callback 函数的第一个元素的值。如果不存在返回 undefined。
    findIndex 它返回数组中找到的元素的索引,而不是其值,如果不存在返回 -15.reduce、reduceRight区别:
   reduce 方法接收两个参数,第一个参数是回调函数(callback) ,第二个参数是初始值(initialValue)。

    reduceRight 方法除了与reduce执行方向相反外(从右往左),其他完全与其一致。
    回调函数接收四个参数:

    accumulator:MDN 上解释为累计器,但我觉得不恰当,按我的理解它应该是截至当前元素,之前所有的数组元素被回调函数处理累计的结果。
    current:当前被执行的数组元素。
    currentIndex: 当前被执行的数组元素索引。
    sourceArray:原数组,也就是调用 reduce 方法的数组。
    
    如果不传入初始值,reduce 方法会从索引 1 开始执行回调函数,如果传入初始值,将从索引 0 开始、并从初始值的基础上累计执行回调。     
    
    注意:
        
            const list  = [
              { name: 'left', width: 20 },
              { name: 'right', width: 10 },
              { name: 'center', width: 70 },
              { name: 'right', width: 10 },
              { name: 'left', width: 20 },
              { name: 'right', width: 10 },
            ];
            
            1.求和
                const total = list.reduce((currentTotal, item) => {
                  return currentTotal + item.width;
                }, 0);
                // total: 140
                
            2.对象数组的去重,并统计每一项重复次数
                const repeatTime = {};
                const result = list.reduce((array, item) => {
                  if (repeatTime[item.name]) {
                    repeatTime[item.name]++;
                    return array;
                  }
                  repeatTime[item.name] = 1;
                  return [...array, item];
                }, []);
                // repeatTime: { left: 2, right: 3, center: 1 }
                // result: [
                //   { name: 'left', width: 20 },
                //   { name: 'right', width: 10 },
                //   { name: 'center', width: 70 },
                // ]

            3.对象数组最大/最小值获取
                const max = list.reduce((curItem, item) => {
                  return curItem.width >= item.width ? curItem : item;
                });
                const min = list.reduce((curItem, item) => {
                  return curItem.width <= item.width ? curItem : item;

                // max: { name: "center", width: 70 }
                // min: { name: "left", width: 20 }
                
             4.reduce 很强大,更多奇技淫巧推荐查看这篇[《25个你不得不知道的数组reduce高级用法》](https://juejin.cn/post/6844904063729926152)
             
    

2.对象