es6新增數(shù)組操作方法在我們拿到后端數(shù)據(jù)的時候,可能會對數(shù)據(jù)進行一些篩選、過濾,傳統(tǒng)的做法如下 // 取出數(shù)組中name為kele的數(shù)組集合 let a = [ { name: 'kele', title: '可口可樂' }, { name: 'kele', title: '芬達' }, { name: 'hn', title: '紅牛' } ] let b = []; for(let i = 0; i < a.length; i++){ if( a[i].name === 'kele' ){ b.push(a[i]) } } console.log(b) //[{name: 'kele', title: '可口可樂'},{name: 'kele', title: '芬達'}] es6中的數(shù)組處理方法如下1,Array.filter(callback) let b = a.filter(item => item.name === 'kele'); console.log(b) //[{name: 'kele', title: '可口可樂'},{name: 'kele', title: '芬達'}] Array.filter()讓我們擺脫了for循環(huán),代碼看起來更加的清爽! 2,Array.find(callback) 這個方法是返回數(shù)組中符合條件的第一個元素,否則就返回undefined let a = [1,2,3,4,5]; let b = a.find(item => item > 2); console.log(b) // 3 傳入一個回調(diào)函數(shù),找到數(shù)組中符合搜索規(guī)則的第一個元素,返回它并終止搜索 const arr = [1, "2", 3, 3, "2"] console.log(arr.find(item => typeof item === "number")) // 1 3,Array.findIndex(callback) 這個方法是返回數(shù)組中符合條件的第一個元素的索引值,否則就返回-1 let a = [1,2,3,4,5]; let b = a.findIndex(item => item > 2); console.log(b) // 2 符合條件的為元素3 它的索引為2 找到數(shù)組中符合規(guī)則的第一個元素,返回它的下標 const arr = [1, "2", 3, 3, "2"] console.log(arr.findIndex(item => typeof item === "number")) // 0 4.from(),將類似數(shù)組的對象(array-like object)和可遍歷(iterable)的對象轉(zhuǎn)為真正的數(shù)組 const bar = ["a", "b", "c"]; Array.from(bar); // ["a", "b", "c"] Array.from('foo'); // ["f", "o", "o"] 5.of(),用于將一組值,轉(zhuǎn)換為數(shù)組。這個方法的主要目的,是彌補數(shù)組構(gòu)造函數(shù) Array() 的不足。因為參數(shù)個數(shù)的不同,會導致 Array() 的行為有差異。 Array() // [] Array(3) // [, , ,] Array(3, 11, 8) // [3, 11, 8] Array.of(7); // [7] Array.of(1, 2, 3); // [1, 2, 3] Array(7); // [ , , , , , , ] Array(1, 2, 3); // [1, 2, 3] 6、entries() 返回迭代器:返回鍵值對 const arr = ['a', 'b', 'c']; for(let v of arr.entries()) { console.log(v) } // [0, 'a'] [1, 'b'] [2, 'c'] //Set const arr = newSet(['a', 'b', 'c']); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b'] ['c', 'c'] //Map const arr = newMap(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.entries()) { console.log(v) } // ['a', 'a'] ['b', 'b'] 8.keys() 返回迭代器:返回鍵值對的key const arr = ['a', 'b', 'c']; for(let v of arr.keys()) { console.log(v) } // 0 1 2 //Set const arr = newSet(['a', 'b', 'c']); for(let v of arr.keys()) { console.log(v) } // 'a' 'b' 'c' //Map const arr = newMap(); arr.set('a', 'a'); arr.set('b', 'b'); for(let v of arr.keys()) { console.log(v) } // 'a' 'b' 9,Array.includes(item, finIndex) includes(),判斷數(shù)組是否存在有指定元素,參數(shù):查找的值(必填)、起始位置,可以替換 ES5 時代的 indexOf 判斷方式。indexOf 判斷元素是否為 NaN,會判斷錯誤。 var a = [1, 2, 3]; let bv = a.includes(2); // true let cv = a.includes(4); // false 10,...擴展運算符 可以很方便的幫我們實現(xiàn)合并兩個數(shù)組 let a = [1,2,3]; let b = [4,5,6]; let c = [...a,...b]; console.log(c) // [1,2,3,4,5,6]; |
|