ES6--數(shù)組擴展

1.Array.of()

{
    let arr=Array.of(3,4,7,8,11);
    console.log(arr)
    // [3, 4, 7, 8, 11]
    let empty=Array.of();
    console.log(empty)
    //[]
}

Array.of() 方法創(chuàng)建一個具有可變數(shù)量參數(shù)的新數(shù)組實例,而不考慮參數(shù)的數(shù)量或類型。
Array.of() 和 Array 構(gòu)造函數(shù)之間的區(qū)別在于處理整數(shù)參數(shù):Array.of(7) 創(chuàng)建一個具有單個元素 7 的數(shù)組,而 Array(7) 創(chuàng)建一個包含 7 個 undefined 元素的數(shù)組。

2.Array.from(),將dom集合轉(zhuǎn)化成數(shù)組,可以用forEach方法遍歷

Array.from方法用于將兩類對象轉(zhuǎn)為真正的數(shù)組:類似數(shù)組的對象(array-like object)和可遍歷(iterable)的對象(包括 ES6 新增的數(shù)據(jù)結(jié)構(gòu) Set 和 Map)。

{
    let p=document.querySelectorAll('p');
    let pArr=Array.from(p);
    pArr.forEach(function(item){
        console.log(item.textContent)
    })
    //111 222 333
    console.log(Array.from([1,3,5],function(item){return item*2}));
    //[2, 6, 10]
}

3.Array.fill()

{
    console.log('fill',[1,'a',undefined].fill(7))
    //[7, 7, 7]
   console.log('fill-2',['a','b','c'].fill(7,1,3));
    //["a", 7, 7] 從起始位置1開始結(jié)束位置3替換成7
}

4.Array的keys(),values(),entries()方法

keys()用來獲取數(shù)組的下標(biāo),values()獲取數(shù)組的值,entries()獲取數(shù)組的下標(biāo)和值

{
    for(let index of ['1','c','ks'].keys()){
        console.log(index)
    }
    //0 1 2
    for(let value of ['1','c','ks'].values()){
        console.log(value)
    }
    //1 c ks 有兼容性問題
    for(let [index,value] of ['1','c','ks'].entries()){
        console.log(index,value)
    }
    //0 1
    //2 c
    //3 ks
}

5.Array.copyWithin()

{
    console.log([1,2,3,4,5].copyWithin(0,3,4))
    //[4, 2, 3, 4, 5]
}

6.Array.find()和Array.findIndex()

數(shù)組實例的find方法,用于找出第一個符合條件的數(shù)組成員。它的參數(shù)是一個回調(diào)函數(shù),所有數(shù)組成員依次執(zhí)行該回調(diào)函數(shù),直到找出第一個返回值為true的成員,然后返回該成員。如果沒有符合條件的成員,則返回undefined。
數(shù)組實例的findIndex方法的用法與find方法非常類似,返回第一個符合條件的數(shù)組成員的位置,如果所有成員都不符合條件,則返回-1。

{
    console.log([1,2,3,4,5,6].find(function(item){
        return item>3;
    }))
    //4 注意find只找出第一個滿足的值
    console.log([1,2,3,4,5,6].findIndex(function(item){
        return item>3;
    }))
    //3 返回符合條件的下標(biāo)
}

7.Array.includes()

{
    console.log([1,2,NaN].includes(1))
    //true
    console.log([1,2,NaN].includes(NaN))
    //true
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容