zoukankan      html  css  js  c++  java
  • js遍历数组的几种方法

    第一种:for循环,也是最常见的

    const arr = [11,22,33,44,55,66,77,88]
    for (let i = 0; i < arr.length; i++) {
                console.log(arr[i])
            }

    第二种:forEach()

     1)、forEach()遍历普通数组

    arr.forEach( function(item){
                console.log(item)
            } )

     2)、forEach()遍历对象类型数组

    const arr = [
                {id:1,name:'zhangsan'},
                {id:2,name:'lisi'},
                {id:3,name:'wangwu'}
            ]
    
    arr.forEach( function(item){
                console.log(item.id + '---' +  item.name)
            })

    输出结果:

    第三种: map()方法

    map即是 “映射”的意思 ,原数组被“映射”成对应新数组

    var newArr = arr.map( function(value,index){
        console.log(value + '---' + index)
        return value + 10
    })

    console.log(newArr)

    输出结果:

    注意:forEach()和map()区别:

    1、forEach:用来遍历数组中的每一项,这个方法执行没有返回值,不影响原数组

    2、map:支持return,相当与原数组克隆了一份,把克隆的每项改变了,也不影响原数组

    第四种: for....in   方法

    for....in 是es5标准, 此方法遍历数组效率低,主要是用来循环遍历对象的属性

    1)、 for......in  遍历数组

    for(let item in arr){
                console.log(arr[item])
            }

    2)、for.....in 遍历对象

    循环遍历对象的属性,js中动态获取key,得到某对象中相对应的value = obj[key]

    const obj = {
                a:1,
                b:2,
                c:3
            }
    
    for(let key in obj){
                console.log(key + '---' + obj[key] )
            }

    输出结果:

    第五种: for.......of    方法    (es6支持)

    for(let item of arr){
                console.log(item)
            }
     
  • 相关阅读:
    Android笔记之spinner的使用
    Android笔记之AlertDialog使用
    Android笔记之intent使用(一)
    Android笔记之Editext使用
    Android控件之Textiew的使用
    Fastboot常用命令集,完美取代Recovery的所有功能
    Android笔记之WebView
    Android程序下重启手机
    Android笔记之ListView组件的使用
    intellij idea设置(字体大小、背景)
  • 原文地址:https://www.cnblogs.com/wangdashi/p/9431860.html
Copyright © 2011-2022 走看看