• js循环遍历数组(对象)


    1,for循环

    对于循环应该是最常用的一种遍历方式了,通常用来遍历数组结构。

    let arr = [a,b,d];
    for (let i=0; i<arr.length; i++){
    console.log(i,arr[i]);
    }


    2,for...in循环

    for...in语句用于对数组或者对象的属性进行循环操作。

    for...in循环中的代码每执行一次,就会对数组或者对象的属性进行一次操作。

    let obj={'name':'programmer','age':'22','height':'180'};
    for(let i in obj){
    console.log(i,obj[i])
    }


    3,while循环

    while用于循环作用基本一致,通常用来循环数组

    cars=["BMW","Volvo","Saab","Ford"];
    var i=0;
    while (cars[i]){
    console.log(cars[i] + "<br>")
    i++;
    };


    4,do while循环

    do while 是while的一个亲戚,它在循环开始前先执行一次操作,然后才进行判断,true就继续执行,false就结束循环。

    let i = 3;
    do{
    console.log(i)
    i--;
    }
    while(i>0);


    5,forEach循环

    forEach方法用于调用数组的每个元素,并将元素传递给回调函数。对于空数组不会执行回调函数。

    let arr = [1,2,3];
    arr.forEach(function(i,index){
    console.log(i,index)
    })
    // 1 0
    // 2 1
    // 3 2


    6,map方法

    map返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

    let arr = [1,2,3];
    let tt = arr.map(function(i){
    console.log(i)
    return i*2;
    })
    // [2,4,6] tt


    7,for...of循环

    因为是es6引入到新特性中的,借鉴c ++,java,c#和python语言,引入for...of循环,作为遍历所有数据结构的统一方法。

    var arr = ['a', 'b', 'c', 'd'];
    for (let a of arr) {
    console.log(a); // a b c d
    }

  • 相关阅读:
    【Linux】创建不可修改文件
    【Linux】文件权限
    【shell】创建长目录,目录存在则忽略,缺失则创建
    【Linux】找出文件之间的差异
    Segment fault及LINUX core dump详解 (zz)
    Segment fault及LINUX core dump详解
    communication ports in DOS systems:
    Ubuntu 16.04 LTS (Xenial Xerus)
    C++ 常见崩溃问题分析
    PC-Lint安装配置与集成到VS2010
  • 原文地址:https://www.cnblogs.com/lgnblog/p/11654512.html
Copyright © 2020-2023  润新知