ES6 for in與for of 的使用方法及其區別


   // for in遍歷的是數組的索引(即鍵名),而for of遍歷的是數組元素值。
 let arr = [1,2,3,4,5,6,7]
    for(let index of arr){
     //   console.log(index)//1 2 3 4 5 6 7
        
    }
    for(let index in arr){
       // console.log(index)//0 1 2 3 4 5 6
        //console.log(arr)//1 2 3 4 5 6 7
        //console.log(arr[index])
    }
    //遍歷對象 通常用for in來遍歷對象的鍵名
    let obj = {
        a:1,
        b:2,
        c:3
    }
    for(let key in obj){
        console.log(key)//a b c 
        //console.log(obj[key])//1 2 3
    }

forEach

  1. 三個參數,第一個value, 第二個 index, 第三個數組體。
  2. 適用於 數組,set,map,不適應於 字符串,Object。
  3. 無法修改和刪除集合數據,效率和for循環相同,不用關心集合下標的返回。
  4. 不能終止循環,break,continue不能使用。
    栗子:
    let arr = [1, "ding", null, 5, true, undefined];
    arr.forEach(function (value, index, a) {
        console.log("value:", value, "index:", index, "a:", a);
    })
 

for in

  1. 索引為字符串
  2. 多用於遍歷對象,json,數組,無順序,增加了轉換過程所以開銷比較大
  3. 可擴展屬性也會遍歷
  4. 支持break, continue
    栗子:
 for (let item in obj) {
        console.log(item, ":", obj[item]);
        if (item == "age") delete obj[item]; //刪除屬性成功
    }
    console.log("obj:", obj);
 
  1. 是目前遍歷數組最好的方法,可以用在set,map,類數組,字符串上,但是不支持原生的Object遍歷。
  2. 支持break, continue



免責聲明!

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



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