zoukankan      html  css  js  c++  java
  • 原生for循环、forEach、for in 、 for of的区别

    1.for循环

    其实除了这三种方法以外还有一种最原始的遍历,自Javascript诞生起就一直用的 就是for循环,它用来遍历数组

    var arr = [1,2,3,4]
    for(var i = 0 ; i< arr.length ; i++){
        console.log(arr[i])
    }

    for循环中可以使用return、break等来中断循环

    2.forEach

    对数组的每一个元素执行一次提供的函数(不能使用return、break等中断循环),不改变原数组,无返回值undefined。

    let arr = ['a', 'b', 'c', 'd']
    arr.forEach(function (val, idx, arr) {
        console.log(val + ', index = ' + idx) // val是当前元素,index当前元素索引,arr数组
        console.log(arr)
    })

    输出结果:

    a, index = 0
    (4) ["a", "b", "c", "d"]
    b, index = 1
    (4) ["a", "b", "c", "d"]
    c, index = 2
    (4) ["a", "b", "c", "d"]
    d, index = 3
    (4) ["a", "b", "c", "d"]

    3.for…in(遍历对象)

    循环遍历的值都是数据结构的键值

    let obj = {a: '1', b: '2', c: '3', d: '4'}
    for (let o in obj) {
        console.log(o)    //遍历的实际上是对象的属性名称 a,b,c,d
        console.log(obj[o])  //这个才是属性对应的值1,2,3,4
    }

    4.for…of(遍历数组)

    它是ES6中新增加的语法

    4.1.遍历数组

    let arr = ['China', 'America', 'Korea']
    for (let o of arr) {
        console.log(o) //China, America, Korea
    }

    4.2.遍历字符串

    let str = 'love'
    for (let o of str) {
        console.log(o) // l,o,v,e
    }

    4.3.遍历一个Map

    let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);
    
    for (let [key, value] of iterable) {
      console.log(value);
    }
    // 1
    // 2
    // 3
    
    for (let entry of iterable) {
      console.log(entry);
    }
    // [a, 1]
    // [b, 2]
    // [c, 3]

    4.4.遍历一个Set

    let iterable = new Set([1, 1, 2, 2, 3, 3]);
    
    for (let value of iterable) {
      console.log(value);
    }
    // 1
    // 2
    // 3
  • 相关阅读:
    COM编程-注册DLL形式的COM服务器
    控制台console使用MFC库函数,Cout输出CString的方法
    [C#]窗体切换--避免开启多个线程
    OpenCV配置使用版
    Dependency Walker使用说明
    TCP粘包和半包的处理方法
    GENERATED_UCLASS_BODY 和 GENERATED_BODY 区别
    c++ 的 坑真多之头文件
    Introduction to replication 翻译
    c++ 的 static_cast
  • 原文地址:https://www.cnblogs.com/pwindy/p/14720907.html
Copyright © 2011-2022 走看看