本文實例講述了ES6中數組array新增方法。分享給大家供大家參考,具體如下:
●find :
let arr=[1,2,234,'sdf',-2];arr.find(function(x){ return x<=2;})//結果:1,返回第一個符合條件的x值arr.find(function(x,i,arr){ if(x<2){console.log(x,i,arr)}})//結果:1 0 [1, 2, 234, "sdf", -2],-2 4 [1, 2, 234, "sdf", -2]find的參數為回調函數,回調函數可以接收3個參數,值x、所以i、數組arr,回調函數默認返回值x。
●findIndex :
let arr=[1,2,234,'sdf',-2];arr.findIndex(function(x){ return x<=2;})//結果:0,返回第一個符合條件的x值的索引arr.findIndex(function(x,i,arr){ if(x<2){console.log(x,i,arr)}})//結果:1 0 [1, 2, 234, "sdf", -2],-2 4 [1, 2, 234, "sdf", -2]findIndex和find差不多,不過默認返回的是索引。
●includes:
let arr=[1,2,234,'sdf',-2];arr.includes(2);// 結果true,返回布爾值arr.includes(20);// 結果:false,返回布爾值arr.includes(2,3)//結果:false,返回布爾值
includes函數與string的includes一樣,接收2參數,查詢的項以及查詢起始位置。
●keys:
let arr=[1,2,234,'sdf',-2];for(let a of arr.keys()){ console.log(a)}//結果:0,1,2,3,4 遍歷了數組arr的索引keys,對數組索引的遍歷
●values:
let arr=[1,2,234,'sdf',-2];for(let a of arr.values()){ console.log(a)}//結果:1,2,234,sdf,-2 遍歷了數組arr的值keys,對數組項的遍歷
●entries:
let arr=['w','b'];for(let a of arr.entries()){ console.log(a)}//結果:[0,w],[1,b]for(let [i,v] of arr.entries()){ console.log(i,v)}//結果:0 w,1 bentries,對數組鍵值對的遍歷。
●fill:
let arr=['w','b'];arr.fill('i')//結果:['i','i'],改變原數組arr.fill('o',1)//結果:['i','o']改變原數組,第二個參數表示填充起始位置new Array(3).fill('k').fill('r',1,2)//結果:['k','r','k'],第三個數組表示填充的結束位置fill方法改變原數組,當第三個參數大于數組長度時候,以最后一位為結束位置。
●Array.of():
Array.of('w','i','r')//["w", "i", "r"]返回數組Array.of(['w','o'])//[['w','o']]返回嵌套數組Array.of(undefined)//[undefined]依然返回數組Array.of()//[]返回一個空數組Array.of()方法永遠返回一個數組,參數不分類型,只分數量,數量為0返回空數組。
●copyWithin:
["w", "i", "r"].copyWithin(0)//此時數組不變["w", "i", "r"].copyWithin(1)//["w", "w", "i"],數組從位置1開始被原數組覆蓋,只有1之前的項0保持不變["w", "i", "r","b"].copyWithin(1,2)//["w", "r", "b", "b"],索引2到最后的r,b兩項分別替換到原數組1開始的各項,當數量不夠,變終止["w", "i", "r",'b'].copyWithin(1,2,3)//["w", "r", "r", "b"],強第1項的i替換為第2項的r
新聞熱點
疑難解答
圖片精選