JavaScript數組循環的幾種寫法,包含ES6

利用Javascript map(),reduce()和filter()數組方法能夠幫助您編寫更加聲明性、流暢的風格代碼。前端

而不是積累起來for循環和嵌套來處理列表和集合中的數據,您能夠利用這些方法更好地將邏輯組織成功能的構建塊,而後將它們連接起來以建立更可讀和更易於理解的實現。es6

ES6還爲咱們提供了一些更好的數組方法,好比.find,.findIndex,.of和for..of循環!json

數組循環

var officers = \[
    { id: 20, name: 'Captain Piett' },
    { id: 24, name: 'General Veers' },
    { id: 56, name: 'Admiral Ozzel' },
    { id: 88, name: 'Commander Jerjerrod' }
\];
// What you need
// \[20, 24, 56, 88\]

for循環

使用率最高,也是最基本的一種遍歷方式數組

var officersIds = \[\];
for(var i=0,len=officers.length;i<len; i++){
    officersIds.push(officers\[i\].id);
}
console.log(officersIds); // \[20,24,56,88\]

forEach循環

forEach中傳入要執行的回調函數,函數有三個參數。第一個參數爲數組元素(必選),第二個參數爲數組元素索引值(可選),第三個參數爲數組自己(可選)微信

var officersIds = \[\];
officers.forEach(function (officer,index,array) {
    console.log(index); //0,1,2,3,
    console.log(officer); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}
    officersIds.push(officer.id);
});
console.log(officersIds); //\[20,24,56,88\]

for in循環

for...in循環可用於循環對象和數組,推薦用於循環對象,能夠用來遍歷JSON函數

var officersIds = \[\];
for(var key in officers){
    console.log(key); // 0 1 2 3 返回數組索引
    console.log(officers\[key\]); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}
    officersIds.push(officers\[key\].id);
}
console.log(officersIds); //\[20,24,56,88\]

for of循環

可循環數組和對象,推薦用於遍歷數組。this

for...of提供了三個新方法:spa

key()是對鍵名的遍歷;
value()是對鍵值的遍歷;
entries()是對鍵值對的遍歷;code

let arr = \['科大訊飛', '政法BG', '前端開發'\];
for (let item of arr) {  
  console.log(item); //  科大訊飛  政法BG  前端開發
}
// 輸出數組索引
for (let item of arr.keys()) {  
  console.log(item);  // 0 1 2
}
// 輸出內容和索引
for (let \[item, val\] of arr.entries()) {  
  console.log(item + ':' + val); //  0:科大訊飛  1:政法BG  2:前端開發
}

var officersIds = \[\];
for (var item of officers) {
    console.log(item); //{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}
    officersIds.push(item.id); 
}
console.log(officersIds); // \[20,24,56,88\]
// 輸出數組索引
for(var item of officers.keys()){
    console.log(item); // 0 1 2 3
}
// 輸出內容和索引
for (let \[item, val\] of officers.entries()) {
    console.log(item) // 0 1 2 3 輸出數組索引
    console.log(val);//{id: 20, name: "Captain Piett"},{id: 24, name: "General Veers"},{id: 56, name: "Admiral Ozzel"},{id: 88, name: "Commander Jerjerrod"}
    console.log(item + ':' + val); 
}

map循環

map() 會返回一個新數組,數組中的元素爲原始數組元素調用函數處理後的值。
map() 方法按照原始數組元素順序依次處理元素。對象

map 不修改調用它的原數組自己。

map()中傳入要執行的回調函數,函數有三個參數。第一個參數爲數組元素(必選),第二個參數爲數組元素索引值(可選),第三個參數爲數組自己(可選)

var arr = \[
    {name:'a',age:'18'},
    {name:'b',age:'19'},
    {name:'c',age:'20'}
\];
arr.map(function(item,index) {
    if(item.name == 'b') {
        console.log(index)  // 1
    }
})

數組加一

var officersIds = officers.map(function (officer) {
    return officer.id
});
console.log(officersIds); //\[20,24,56,88\]

reduce

array.reduce(function callback(accumulator, currentValue, currentIndex, array){

}\[, initialValue\])

var peoples = \[
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
    id: 41,
    name: "Tallissan Lintra",
    years: 16,
  },
  {
    id: 99,
    name: "Ello Asty",
    years: 22,
  }
\];

輸出他們的年齡總數

var totalYears = peoples.reduce(function (total, people) {
    console.log(total);
    console.log(people);
    return total + people.years;
}, 0);
// const totalYears = people.reduce((acc, people) => acc + people.years, 0);
console.log(totalYears); //30

求年齡最大的那我的

var oldest = peoples.reduce(function (oldest, people) {
    return (oldest.years || 0) > people.years ? oldest : people;
}, {});
console.log(oldest); //{id: 2, name: "Temmin 'Snap' Wexley", years: 30}
console.log(oldest.years); //82

filter

filter() 方法建立一個新的數組,新數組中的元素是經過檢查指定數組中符合條件的全部元素。

array.filter(function(currentValue,index,arr){

}, thisValue)

演示

var designer = peoples.filter(function (people) {
    return people.job === "designer";
});

組合使用

var totalScore = peoples
    .filter(function (person) {
        return person.isForceUser;
    })
    .map(function (choose) {
        return choose.mathScore + choose.englishScore;
    })
    .reduce(function (total, score) {
        return total + score;
    }, 0);

Array.from()

var divs = document.querySelectorAll('div.pane');  
var text = Array.from(divs, (d) => d.textContent);  
console.log("div text:", text);

// Old, ES5 way to get array from arguments
function() {  
  var args = \[\].slice.call(arguments);
  //...
}

// Using ES6 Array.from
function() {  
  var args = Array.from(arguments);
  //..
}

var filled = Array.from(\[1,,2,,3\], (n) => n || 0);  
console.log("filled:", filled);  
// =\> \[1,0,2,0,3\]

加入微信羣👆,每日分享全網好文章!

相關文章
相關標籤/搜索