zoukankan      html  css  js  c++  java
  • js 中的forEach,for in ,for of 的使用

    推荐在循环对象属性的时候,使用for...in,在遍历数组的时候的时候使用for...of

    1.for in 遍历对象的key

    一般不推荐遍历数组,因为for in遍历后的不能保证顺序,而且原型链上的属性也会被遍历到,

    因此一般常用来遍历非数组的对象并且使用hasOwnProperty()方法去过滤掉原型链上的属性

    2.for of 遍历对象的value,只循环集合本身的元素:

     与forEach()不同的是,它可以正确响应break、continue和return语句

            Object.prototype.age = function () {}; 
            var arr = ['A', 'B', 'C'];
            arr.name = 'Hello';
            for (var index in arr) {
                console.log(index); // '0', '1', '2', 'name','age'
            } 
            
            for (var value of arr) {
                console.log(value); // 'A', 'B',
                 if(value=='B'){
                    break;
                }
            } 
            arr.forEach((value,index,arr)=>{
                console.log(value);
                if(value=='B'){
                    break;  //Uncaught SyntaxError:Illegal break statement
                }
            })
  • 相关阅读:
    (57)C# frame4 调用frame2
    (56)C# 读取控制台程序
    (55)C# windows 消息
    (54) C# 调用 kernel32.dll
    (53)C# 工具
    C++ hello world
    postgresql时间处理
    ext中grid根据数据不同显示不同样式
    log4j入门
    敏感数据加密
  • 原文地址:https://www.cnblogs.com/yuesu/p/9799096.html
Copyright © 2011-2022 走看看