JavaScript數組循環


JavaScript數組循環

一、前言

利用Javascript map(),reduce()filter()數組方法可以遍歷數組。而不是積累起來for循環和嵌套來處理列表和集合中的數據,利用這些方法可以更好地將邏輯組織成功能的構建塊,然后將它們鏈接起來以創建更可讀和更易於理解的實現。ES6提供了一些更好的數組方法,比如.find,.findIndex,.offor..of循環

 

二、具體實現

1.數組循環

var officers = [s

    { id: 20, name: 'Captain' },

    { id: 24, name: 'General' },

    { id: 56, name: 'Admiral' },

    { id: 88, name: 'Commander' }

];

 

2.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]

 

3.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]

4.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]

5.for of循環

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

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

key()是對鍵名的遍歷;

value()是對鍵值的遍歷;

entries()是對鍵值對的遍歷;

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);

}

6.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

    }

})

7.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]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM