ES6新增數組的方法

es6新增數組操作方法

在我們拿到後端數據的時候,可能會對數據進行一些篩選、過濾,傳統的做法如下

// 取出數組中name爲kele的數組集合
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中的數組處理方法如下

1,Array.filter(callback)

let b = a.filter(item => item.name === 'kele');
 
console.log(b) //[{name: 'kele', title: '可口可樂'},{name: 'kele', title: '芬達'}]

Array.filter()讓我們擺脫了for循環,代碼看起來更加的清爽!

 2,Array.find(callback)

這個方法是返回數組中符合條件的第一個元素,否則就返回undefined

let a = [1,2,3,4,5];
let b = a.find(item => item > 2);
console.log(b)  // 3

傳入一個回調函數,找到數組中符合搜索規則的第一個元素,返回它並終止搜索

const arr = [1, "2", 3, 3, "2"]
console.log(arr.find(item => typeof item === "number")) // 1

3,Array.findIndex(callback)

這個方法是返回數組中符合條件的第一個元素的索引值,否則就返回-1

let a = [1,2,3,4,5];
let b = a.findIndex(item => item > 2);
console.log(b) // 2 符合條件的爲元素3 它的索引爲2

找到數組中符合規則的第一個元素,返回它的下標

const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(item => typeof item === "number")) // 0

4.from(),將類似數組的對象(array-like object)和可遍歷(iterable)的對象轉爲真正的數組

const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]

Array.from('foo');
// ["f", "o", "o"]

5.of(),用於將一組值,轉換爲數組。這個方法的主要目的,是彌補數組構造函數 Array() 的不足。因爲參數個數的不同,會導致 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(),判斷數組是否存在有指定元素,參數:查找的值(必填)、起始位置,可以替換 ES5 時代的 indexOf 判斷方式。indexOf 判斷元素是否爲 NaN,會判斷錯誤。

var a = [1, 2, 3];
let bv = a.includes(2); // true
let cv = a.includes(4); // false

10,...擴展運算符

可以很方便的幫我們實現合併兩個數組

let a = [1,2,3];
let b = [4,5,6];
let c = [...a,...b];
console.log(c) // [1,2,3,4,5,6];

 其它人寫的參考:https://segmentfault.com/a/1190000019131088

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章