遍歷數組的幾種方式


1.for 循環

for(j = 0; j < arr.length; j++) {
   
} 

 

2.forEach   最簡單、最常用的數組遍歷方法。它提供一個回調函數,可用於處理數組的每一個元素,默認沒有返回值。 遍歷開始以后無法停止。

arr.forEach(function(e){  
   
});

 

3.map 會映射返回一個新數組,不會改變原數組的值

var array = arr.map((item,index)=>{
    
})

 

4.filter 過濾數組,返回一個新的數組,原數組的元素執行了回調函數之后返回值若為true,則會將這個元素放入返回的數組中。

var newarr = arr.filter((item,index)=>{
   return 條件 
})
// 例子:篩選出數組arr中所有負數
var arr = [1,-2,3,4,-5]
var minus = arr.filter(function(item,index,array){
    return item < 0;
});
console.log(minus);   // [-2, -5]

 

5.some 遍歷整個數組,返回值true就停止循環(返回false繼續循環)返回布爾值 多用於判斷數組中是否存在

arr.every(function(value, index, array){
    // arr中有幾項,該匿名回調函數就需要執行幾次
    // value —— 數組中的當前項
    // index —— 當前項的索引
    // array —— 原始數組
    return xxx
})

//例子:判斷arr中的元素是否都為正數
var arr = [1,-2,3,4,-5]
var isEvery = arr.every(function(item, index, array){
    return item > 0
})
console.log(isEvery) // false

 

6.every 與some相反,返回false就停止循環(返回true就繼續循環) 返回的是一個布爾值 多用於判斷數組中是否存在之類

arr.some(function(value, index, array){
    // arr中有幾項,該匿名回調函數就需要執行幾次
    // value —— 數組中的當前項
    // index —— 當前項的索引
    // array —— 原始數組
    return xxx
})

//例子:判斷數組arr中是否存在負數
var arr = [1,-2,3,4,-5]
var isSome = arr.some(function(item,index,array){
    return item < 0;
});
console.log(isSome);   // true

 

7.reduce 實現數據的累加

arr.reduce(function(prev, cur, index, array){
    // array——原數組
    // prev——上一次調用回調時的返回值,或者初始值init
    // cur——當前正在處理的數組元素
    // index——當前正在處理的數組元素的索引
    // init——初始值
}, init)

//求和
var sum = arr.reduce(function (prev, cur) {
    return prev + cur;
},0);

//取最大值
var max = arr.reduce(function (prev, cur) {
    return Math.max(prev,cur);
});

 

8.for..of ES6中,新增了for-of遍歷方法。它被設計用來遍歷各種類數組集合,例如DOM NodeList對象、Map和Set對象,甚至字符串也行。

// for-of遍歷數組,不帶索引,i即為數組元素
for ( let  i of arrTmp){
     console.log(i)
}
//輸出 "value1" "value2" "value3"
 
// for-of遍歷Map對象
let  iterable =  new  Map([[ "a" , 1], [ "b" , 2], [ "c" , 3]]);
for  ( let  [key, value] of iterable) {
   console.log(value);
}
//輸出 1 2 3
 
// for-of遍歷字符串
let  iterable =  "china中國" ;
for  ( let  value of iterable) {
   console.log(value);
}
//輸出 "c" "h" "i" "n" "a" "中" "國"

順帶記錄以下for...of...與for..in...的區別

for...in...只能獲得對象的鍵名,不能獲得鍵值

for...of...允許遍歷獲得鍵值

var arr = ['red', 'green', 'blue']
 
for(let item in arr) {
  console.log('for in item', item)
}
/*
  for in item 0
  for in item 1
  for in item 2
*/
 
for(let item of arr) {
  console.log('for of item', item)
}
/*
  for of item red
  for of item green
  for of item blue
*/

 


免責聲明!

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



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