es6数组

作者: 没有昵_称 | 来源:发表于2020-12-11 16:42 被阅读0次

    Array.from()

    将类数组转成真正的组转

    let ArrayLike = {
        '0': 'a',
        '1': 'b',
        '2': 'c',
        length: 3
    }
    console.log(Array.from(ArrayLike,x=>x+'xx'))
                // 等价于
    console.log(Array.from(ArrayLike).map(x=>x+'xx'))
    

    Array.of()

    将一维数转成数组

    console.log(Array.of(1,2,3)) //[1,2,3]
    console.log(Array.of(1,2,3).length) //3         
    

    find

    找到第一个符合条件的数组

    console.log([1,2,3,4,5].find((value,index,arr)=>value<1)) //undefined
    console.log([1,2,3,4,5].find((value,index,arr)=>value<3)) //1
    

    findIndex

    和find类似,他是返回第一个符合条件的下标

    console.log([1,2,3,4,5].findIndex((value,index,arr)=>value<1)) //-1
    console.log([1,2,3,4,5].findIndex((value,index,arr)=>value<3)) //0
    

    for...of

    keys() values() entries()

    for(let i of ['a','b'].values()){console.log(i)} //a,b
    for(let i of ['a','b'].keys()){console.log(i)} //0,1
    for(let [index,value] of ['a','b'].entries()){console.log(index,value)} //0 a,1 b
    

    includes

    返回一个布尔值,判断数据是否有某数据,和字符串的includes类似
    includes 的第二个参数表示搜索的起始位置

    console.log('abc'.includes('a')) //true
    console.log(['a','b'].includes('a')) //true
    console.log(['a','b'].includes('a',0)) //true
    console.log(['a','b'].includes('a',1)) //false
    

    数组空值

    • for...of 会遍历数组空位,forEach(),filter(),every(),map()some()会跳过数据空位
    for(let i of [,,,]){
        console.log(1)
    }//1,1,1
    
    • Array.from(),扩展运算符(...)都会把数组空位转成undefined
    console.log([...[,,,]]) //[undefined,undefined,undefined]
    console.log(Array.from([,,,])) //[undefined,undefined,undefined]
    
    • jointoString,会把数据空位视为undefined,而undefinednull会处理成空串
    console.log([,,,1].join("*"))//***1
    console.log([,,,2].toString())//,,,2
    
    • entries()keys()values()find()findIndex()会将空位处理成undefined
    console.log([...[,'a'].keys()]) //[0, 1]
    console.log([...[,'a'].values()]) //[undefined, "a"]
    console.log([...[,'a'].entries()]) //[[0, 1],[undefined, "a"]]
    [,'a'].find(x => true) // undefined
    [,'a'].findIndex(x => true) // 0
    

    相关文章

      网友评论

          本文标题:es6数组

          本文链接:https://www.haomeiwen.com/subject/kpyjgktx.html