JavaScript遍歷對象-總結一


原生JavaScript 遍歷

  1、for 循環遍歷 

1 let array1 = ['a','b','c'];
2 
3 for (let i = 0;i < array1.length;i++){
4   console.log(array1[i]);  // a  b  c 
5 }

  2、JavaScript 提供了 foreach()  map() 兩個可遍歷 Array對象 的方法

    forEach和map用法類似,都可以遍歷到數組的每個元素,而且參數一致;   

Array.forEach(function(value , index , array){ //value為遍歷的當前元素,index為當前索引,array為正在操作的數組
  //do something
},thisArg)      //thisArg為執行回調時的this值

    不同點:

                   forEach() 方法對數組的每個元素執行一次提供的函數。總是返回undefined;

            map() 方法創建一個新數組,其結果是該數組中的每個元素都調用一個提供的函數后返回的結果。返回值是一個新的數組;

             例子如下:

    var array1 = [1,2,3,4,5];

    var x = array1.forEach(function(value,index){

        console.log(value);   //可遍歷到所有數組元素

        return value + 10
    });
    console.log(x);   //undefined    無論怎樣,總返回undefined

    var y = array1.map(function(value,index){

        console.log(value);   //可遍歷到所有數組元素

        return value + 10
    });
    console.log(y);   //[11, 12, 13, 14, 15]   返回一個新的數組

  

  對於類似數組的結構,可先轉換為數組,再進行遍歷

  

let divList = document.querySelectorAll('div');   //divList不是數組,而是nodeList

//進行轉換后再遍歷
[].slice.call(divList).forEach(function(element,index){
  element.classList.add('test')
})


Array.prototype.slice.call(divList).forEach(function(element,index){
  element.classList.remove('test')
})

[...divList].forEach(function(element,index){   //ES6寫法
  //do something
})

 

  3、 for ··· in ···     /      for ··· of ···

     for...in 語句以任意順序遍歷一個對象的可枚舉屬性。對於每個不同的屬性,語句都會被執行。每次迭代時,分配的是屬性名  

     補充 : 因為迭代的順序是依賴於執行環境的,所以數組遍歷不一定按次序訪問元素。 因此當迭代那些訪問次序重要的 arrays 時用整數索引去進行 for 循環 (或者使用 Array.prototype.forEach() 或 for...of 循環) 。

let array2 = ['a','b','c']
let obj1 = {
  name : 'lei',
  age : '16'
}

for(variable  in array2){   //variable  為 index
  console.log(variable )   //0 1 2
}

for(variable  in obj1){   //variable 為屬性名
  console.log(variable)   //name age
}

  

      ES6新增了 遍歷器(Iterator)機制,為不同的數據結構提供統一的訪問機制。只要部署了Iterator的數據結構都可以使用 for ··· of ··· 完成遍歷操作  ( Iterator詳解 :  http://es6.ruanyifeng.com/#docs/iterator ),每次迭代分配的是 屬性值

           原生具備 Iterator 接口的數據結構如下:

      Array   Map Set String TypedArray 函數的arguments對象 NodeList對象

let array2 = ['a','b','c']
let obj1 = {
  name : 'lei',
  age : '16'
}

for(variable  of array2){   //variable  為 value
  console.log(variable )   //'a','b','c'
}

for(variable  of obj1){  //普通對象不能這樣用
  console.log(variable)   // 報錯 : main.js:11Uncaught TypeError: obj1[Symbol.iterator] is not a function
}

let divList = document.querySelectorAll('div');

for(element of divlist){ //可遍歷所有的div節點
  //do something
}

  如何讓普通對象可以用for of 進行遍歷呢?  http://es6.ruanyifeng.com/#docs/iterator  一書中有詳細說明了!

 

  除了迭代時分配的一個是屬性名、一個是屬性值外,for in 和 for of 還有其他不同    (MDN文檔: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of)

    for...in循環會遍歷一個object所有的可枚舉屬性。

      for...of會遍歷具有iterator接口的數據結構

      for...in 遍歷(當前對象及其原型上的)每一個屬性名稱,而 for...of遍歷(當前對象上的)每一個屬性值

  

Object.prototype.objCustom = function () {}; 
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for (let i in iterable) {
  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

for (let i of iterable) {
  console.log(i); // logs 3, 5, 7
}

 

    

  


免責聲明!

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



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