ES6經常使用數據方法總結

1. forEach()

let array = [1,2,3,4];
array.forEach((item, index, array) => {
  console.log(item);
});
forEach會遍歷數組, 沒有返回值, 不容許在循環體內寫return, 不會改變原來數組的內容.

2. map()

let array = [1, 2, 3, 4];
let temp = array.map((item, index, array) => {
    return item * 10;
});
console.log(temp);  //  [10, 20, 30, 40];
console.log(array);  // [1, 2, 3, 4]
map 遍歷數組, 會返回一個新數組, 不會改變原來數組裏的內容
let temp2 = array.map(String);  // 把數組裏的元素都轉成字符串

3. filter()

let array = [1, 2, 3, 4];
let temp = array.filter((item, index, array) => {
  return item >  3;
});
console.log(temp);  // [4]
console.log(array);  // [1, 2, 3, 4]
filter 會過濾掉數組中不知足條件的元素, 把知足條件的元素放到一個新數組中, 不改變原數組

4. reduce()

let array = [1, 2, 3, 4];
let temp = array.reduce((x, y) => {
  console.log("x": x);
  console.log("y": y);
  return x + y;
});
console.log(temp);  // 10
console.log(array);  // [1, 2, 3, 4]
x 是上一次計算過的值, 第一次循環的時候是數組中的第1個元素
y 是數組中的每一個元素, 第一次循環的時候是數組的第2個元素

5. every()

let array = [1, 2, 3, 4];
let bo = array.every((item, index, array) => {
  return item > 2;
});
console.log(bo);    // false;
every遍歷數組, 每一項都是true, 則返回true,只要有一個是false,就返回false

6. some()

let array = [1, 2, 3, 4];
let tmep = array.some((item, index, array) => {
  return item > 1;
});
console.log(temp);  // true
遍歷數組的每一項, 有一個返回true, 就中止循環

7.values()

let arr=[1,2,234,'sdf',-2];
for(let a of arr.values()){
    console.log(a) //結果:1,2,234,sdf,-2 遍歷了數組arr的值
}
values,對數組項的遍歷

8.keys()

let arr=[1,2,234,'sdf',-2];
for(let a of arr.keys()){
    console.log(a) //結果:0,1,2,3,4  遍歷了數組arr的索引
}
keys,對數組索引的遍歷

9.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 b
}
entries,對數組鍵值對的遍歷。

以上9個方法IE9及以上才支持。不過能夠經過babel轉義支持IE低版本。
以上均不改變原數組。
some、every返回true、false。
map、filter返回一個新數組。
reduce讓數組的先後兩項進行某種計算,返回最終操做的結果。
forEach 無返回值。數組

相關文章
相關標籤/搜索