zoukankan      html  css  js  c++  java
  • for...of与for...in的区别

    for...in

    for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性

    var obj = {a:1, b:2, c:3};
    
    for (var prop in obj) {
      console.log("obj." + prop + " = " + obj[prop]);
    }
    
    // Output:
    // "obj.a = 1"
    // "obj.b = 2"
    // "obj.c = 3"
    

    for...of

    for...of语句在可迭代对象(包括 Array,Map,Set,String,TypedArray,arguments 对象等等)上创建一个迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句
    注意:循环迭代并记录iterable作为可迭代对象定义的迭代值,这些是数组元素 3, 5, 7,而不是任何对象的属性

    const array1 = ['a', 'b', 'c'];
    
    for (const element of array1) {
      console.log(element);
    }
    

    不同点

    for of 只遍历iterable定义的迭代值,并且不能遍历对象,
    for in 遍历迭代对象可枚举的值,所以包括继承,还有定义的属性

    Object.prototype.objCustom = function () {};
          Array.prototype.arrCustom = function () {};
    
          let iterable = [3, 5, 7];
          iterable.foo = "hello";
          for (let key in iterable) {
            console.log(key, "in");//0, 1, 2, "foo", "arrCustom", "objCustom"
          }
          for (let key of iterable) {
            console.log(key, "of");//3, 5, 7
          }
    
  • 相关阅读:
    Data Security---->Control Access to the Organization
    Data Modeling
    Slaesforce Paltform Development Basic
    Customize your Chatter Experience.
    wamp自定义网站根目录及多站点配置
    1053-1055
    1046-1052
    1044-1045
    HDOJ 1038-1043
    HDOJ 1031-1037
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/14794167.html
Copyright © 2011-2022 走看看