博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
JavaScript遍历循环
阅读量:6891 次
发布时间:2019-06-27

本文共 1666 字,大约阅读时间需要 5 分钟。

  hot3.png

定义一个数组和对象

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];const obj = {    a: 1,    b: 2,    c: 3,    d: 4}

for()

经常用来遍历数组元素

遍历值为数组元素索引

for (let i = 0, len = arr.length; i < len; i++) {    console.log(i);            // 0 1 2 3 4 5    console.log(arr[i]);     // a b c d e f}

forEach()

用来遍历数组元素

第一个参数为数组元素,第二个参数为数组元素索引,第三个参数为数组本身(可选)
没有返回值

arr.forEach((item, index) => {    console.log(item);     // a b c d e f     console.log(index);   // 0 1 2 3 4 5})

map()

用来遍历数组元素

第一个参数为数组元素,第二个参数为数组元素索引,第三个参数为数组本身(可选)
有返回值,返回一个新数组

every(),some(),filter(),reduce(),reduceRight()不再一一介绍

let arrData = arr.map((item, index) => {    console.log(item);     // a b c d e f     console.log(index);   // 0 1 2 3 4 5    return item;})console.log(arrData);    // ["a", "b", "c", "d", "e", "f"]

for...in 

可循环对象和数组,推荐用于循环对象

 

1.循环值为对象属性

for (let key in obj) {    if (obj.hasOwnProperty(key)) {        console.log(key);           // a b c d  属性        console.log(obj[key]);    // 1 2 3 4  属性值    }}

2.值为数组索引

for (let index in arr) {    console.log(index);          // 0 1 2 3 4 5 数组索引    console.log(arr[index]);   // a b c d e f 数组值}

当我们给数组添加一个属性name

arr.name = '我是自定义的属性'

for (let index in arr) {    console.log(index);           // 0 1 2 3 4 5 name (会遍历出我们自定义的属性)    console.log(arr[index]);    // a b c d e f 我是自定义属性name}

for...of

可循环对象和数组,推荐用于遍历数组

 

1.遍历值为数组元素

for (let value of arr) {    console.log(value);       // a b c d e f 数组值}

2.遍历对象时须配合Object.keys()一起使用,直接用于循环对象会报错,不推荐使用for...of循环对象

循环值为对象属性

for (let value of Object.keys(obj)) {    console.log(value);    // a b c d 对象属性}

总结

  • 用于遍历数组元素使用:for(),forEach(),map(),for...of
  • 用于循环对象属性使用:for...in

转载于:https://my.oschina.net/incess/blog/3045275

你可能感兴趣的文章
MUI功能列表
查看>>
video 全屏时 隐藏controls
查看>>
python input() 与raw_input()
查看>>
mysql数据库 --表查询
查看>>
Python中xlrd常用用法整理
查看>>
如何上传本地音乐获取MP3外链(欢迎分享和转载)
查看>>
@vue/cl构建得项目下,postcss.config.js配置,将px转化成rem
查看>>
搭建gitlab本地服务
查看>>
day02
查看>>
SpringBoot慕课学习-SpringBoot开发常用技术整合-资源文件属性配置
查看>>
命令导入证书
查看>>
Django-CBV
查看>>
NativeWindow_01
查看>>
【Flutter学习】基本组件之图片组件Image
查看>>
(转)工作之路---记录LZ如何在两年半的时间内升为PM
查看>>
CoreAnimation
查看>>
JS基础属性跟运算
查看>>
通过类创建子线程&同步锁
查看>>
编程珠玑:单词频率最高选取
查看>>
几乎所有编程语言的hello, world程序(3)
查看>>