JS幾種數組遍歷方式,高階方法


一、forEach()

遍歷數組,無返回值。理論上該方法沒有返回值,僅僅是遍歷數組中的每一項,不對原數組進行修改;但是可以通過數組的索引來修改原來的數組

方法中傳入的 匿名回調函數中的this指向window

arr.forEach(function(value, index, array){
	// arr中有幾項,該匿名回調函數就需要執行幾次
	// value —— 數組中的當前項
	// index —— 當前項的索引
	// array —— 原始數組
})
例子:
var arr = [1,2,3,4,5]
var res = arr.forEach(function(item, index, arr){
	arr[index] = item*2
})
console.log(res) //undefined
conosle.log(arr) //[2,4,6,8,10],通過數組索引改變了原數組

二、map()

遍歷數組,有返回值。map的回調函數中支持return返回值,即把原數組克隆一份,把克隆的數組中對應項進行修改

方法中傳入的 匿名回調函數中的this指向window

arr.map(function(value, index, array){
	// arr中有幾項,該匿名回調函數就需要執行幾次
	// value —— 數組中的當前項
	// index —— 當前項的索引
	// array —— 原始數組
	return xxx
})
var ary = [1,2,3,4,5];  
var res = ary.map(function (item,index,input) {  
    return item*10;  
})  
console.log(res);//-->[1,2,3,4,5];  原數組拷貝了一份,並進行了修改
console.log(ary);//-->[10,20,30,40,50];  原數組並未發生變化

三、every()

遍歷數組,判斷數組中的每一項元素是否都滿足條件,返回一個布爾值

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

四、some()

遍歷數組,判斷數組中的是否存在滿足條件的元素,返回一個布爾值

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

五、filter()

遍歷數組,篩選數組中滿足條件的元素,返回一個篩選后的新數組

arr.filter(function(value, index, array){
	// arr中有幾項,該匿名回調函數就需要執行幾次
	// value —— 數組中的當前項
	// index —— 當前項的索引
	// array —— 原始數組
	return xxx
})
// 例子:篩選出數組arr中所有負數
var arr = [1,-2,3,4,-5]
var minus = arr.filter(function(item,index,array){
    return item < 0;
});
console.log(minus);   // [-2, -5]

補充

(1)以上五大方法除了傳遞一個匿名函數作為參數之外,還可以傳第二個參數,該參數用於指定匿名函數內的this指向

//例子
// 只傳一個匿名函數
var arr = [1,-2,3,4,-5]
arr.forEach(function(item,index,array){
    console.log(this);  // window
});
// 傳兩個參數
arr.forEach(function(item,index,array){
    console.log(this);  // [1, -2, 3, 4, -5]
},arr);

(2)由於以上方法均屬ES5方法,所以IE8及其以下瀏覽器均不兼容。

六、reduce()

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

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

    由於傳入了初始值0,所以開始時prev的值為0,cur的值為數組第一項3,相加之后返回值為3作為下一輪回調的prev值,然后再繼續與下一個數組項相加,以此類推,直至完成所有數組項的和並返回。

  • 2)求數組項最大值

    var max = arr.reduce(function (prev, cur) {
        return Math.max(prev,cur);
    });
    

    由於未傳入初始值,所以開始時prev的值為數組第一項3,cur的值為數組第二項9,取兩值最大值后繼續進入下一輪回調。

  • 3)數組去重

    	var arr = [1, 1, 3, 4, 5, 8, 8, 9, 10, 10]
        var newArr = arr.reduce(function (prev, cur) {
          prev.indexOf(cur) === -1 && prev.push(cur);
          return prev;
        }, []);
        console.log(newArr) // [1, 3, 4, 5, 8, 9, 10]
    

    補充:||&&兩端是表達式

    • 1)||操作符從左開始判斷表達式的真假,如果為真,返回左邊表達式返回的值;如果為假,則繼續判斷右邊的表達式

    • 2)&&操作符從左開始判斷表達式, 如果左邊的表達式被判斷為假, 這馬上返回false, 不管右邊的表達式是否為真;如果左邊的表達式為真, 則繼續判斷右邊的表達式, 然后返回右邊表達式結果

    • // demo1
      if(userName){
        login(userName)
      }else{
        signUp()
      }
      // 換成以下寫法
      userName && login(userName) || signUp()
      
    • // demo2
      var userID;
      if (userName && userName.loggedIn) {
      userID = userName.id;
      } else {
      userID = null;
      }
      // 換成以下寫法
      var userID = userName && userName.loggedIn && userName.id
      
  • 4)求字符串中字母出現的次數

    let str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmx';
    let res = str.split('').reduce(
    	(hash, cur) => {
    		hash[cur] ? hash[cur]++ : hash[cur] = 1
    		return hash
    	}, {}
    )
    
  • 5)將數組按一定的規則轉成數組

    // 每個值的平方
    let arr = [1,2,3,4]
    let newArr = arr.reduce(
    	(arr, cur) => {
    		arr.push(cur * cur)
    		return arr
    	}, []
    )
    
  • 6)扁平一個二維數組

    let arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];
    let res = arr.reduce((x, y) => x.concat(y), []);
    


免責聲明!

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



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