ES6數組可以支持下面的幾種寫法:
(1)var [a,b,c] = [1,2,3]; (2)var [a,[[b],c]] = [1,[[2],3]]; (3)let [x,,y] = [1,2,3]; //x=1 y=3 (4)var [x,...y] = [1,2,3,4]; //x=1 y=[2,3,4]
當然我認為代碼必須要有易讀性,所以請謹慎選擇寫法。
下面就要說數組的方法
轉換成數組的方法Array.from()這個方法是把類似數組的對象或者是可遍歷的對象轉化為數組(包括了ES6里面的Set和Map方法)如果參數是一個數組則會返回一個一模一樣的數組,這個方法如果傳入的是一個字符串那么他會把傳入的字符串拆開並返回。
代碼示例
var shuzu = { '0' : "h", '1' : "e", '2' : "l", '3' : "l", '4' : "o", length : 3,//要輸出的長度 }; console.log(Array.from(shuzu)); //[ 'h', 'e', 'l' ] console.log(Array.from(shuzu).length); //3 console.log(Array.from('apple')); //[ 'a', 'p', 'p', 'l', 'e' ] console.log(Array.from('apple').length); //5
如果是將一堆值轉化為數組使用Array.of()
console.log(Array.of(1,2,3));//[ 1, 2, 3 ] console.log(Array.of(1,2,3).length);//3
如果是復制當前數組某值到當前數組的某個位置使用copyWithin()會返回一個新的數組,接受三個參數依次為從該位置開始替換數據、從該位置開始讀取數據和到該位置前停止讀取數據。
console.log([0,1,2,3,4,5,6].copyWithin(0)); //[ 0, 1, 2, 3, 4, 5, 6 ] console.log([0,1,2,3,4,5,6].copyWithin(0,2)); //[ 2, 3, 4, 5, 6, 5, 6 ] //舍棄第二位以前的后面的補位並把后位用最后的兩位補齊 console.log([0,1,2,3,4,5,6].copyWithin(0,2,3)); //[ 2, 1, 2, 3, 4, 5, 6 ] //把原第三位補至原第零位其他位不變 console.log([0,1,2,3,4,5,6].copyWithin(0,2,4)); //[ 2, 3, 2, 3, 4, 5, 6 ] //把原第二位第三位補至原第零位和第一位 console.log([0,1,2,3,4,5,6].copyWithin(0,2,5)); //[ 2, 3, 4, 3, 4, 5, 6 ] //把原第二三四位補至原第零一二位
判斷該數組是否含有某值使用find()方法,這個方法有三個參數value(尋找的值)、index(從哪開始)、arr(原數組),這個方法用於找出第一個符合條件的數組成員並返回該值。
console.log([1,2,3,4].find((n) => n<4)); //1 console.log([1,2,3,4].find(function (value,index,arr) {return value<4 ;})); //1
如果要把數組內部全部替換並返回一個新的數組使用fill()方法,這個方法接受三個參數value(要填充的值)、start(從哪里填充)、end(填充到哪)。
console.log([1,2,3].fill('a')); //[ 'a', 'a', 'a' ] console.log([0,1,2].fill('a',1,3)); //[ 0, 'a', 'a' ] //如果結束位大於等於數組的長度那么會從開始為到結束位都填充上填充的值 console.log([0,1,2,3,4].fill('a',1,3)); //[ 0, 'a', 'a', 3, 4 ] /*也可以這么寫*/ console.log(new Array(3).fill('a')); //[ 'a', 'a', 'a' ]
如果你要遍歷數組那么有三個方法可供選擇entries()、keys()、values(),都返回一個遍歷器對象,可以用for...of循環遍歷,他三個不同的是keys()對鍵名的遍歷,values()是對值的遍歷,entries()是對鍵值對的遍歷。
for(let index of [ 'test' , 'ceshi' , 'apple' ].keys()){ console.log(index); } // 0 1 2 for(let [index,values] of [ 'test' , 'ceshi' , 'apple' ].entries()){ console.log(index,values); }//0 'test' 1 'ceshi' 2 'apple' for(let values of [ 'test' , 'ceshi' , 'apple' ].values()){ console.log(values); } //報錯!!!也不知道為什么我的不支持這個函數,如果有發現這個問題怎么解決請在后面留言 Thanks?(?ω?)?
如果查看數組里面是否含有某值使用includes()他會返回一個布爾值,有兩個參數values(值)、start(從第幾個開始)。
console.log([1,2,3].includes(1));//true console.log([1,2,3].includes(1,2));//false
數組推導允許直接通過現有的數組生成新的數組,有點像vue里面的 x of y
var nums = [1,2,3,4,5,6]; for (num of nums) if(num>2){ console.log(num); } ; //3 4 5 6