• 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
          }
    
  • 相关阅读:
    326. Power of Three
    python实现Excel删除特定行、拷贝指定行操作
    283. Move Zeroes
    268. Missing Number
    263. Ugly Number
    258. Add Digits
    257. Binary Tree Paths
    二叉树的创建,递归前序、中序、后序遍历以及队列实现层遍历
    242. Valid Anagram
    237. Delete Node in a Linked List
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/14794167.html
Copyright © 2020-2023  润新知