JavaScript循环遍历

比眉伴天荒 2023-10-06 19:34 156阅读 0赞

JavaScript循环遍历

  • for() 遍历数组元素
  • forEach() 遍历数组元素
  • map() 遍历数组元素
  • for…in 可循环对象和数组,推荐用于循环对象
    • 1.循环值为对象属性
    • 2.值为数组索引
    • for…of 可循环对象和数组,推荐用于遍历数组
      • 1.遍历值为数组元素
      • 2.循环值为对象属性
  • 总结

    const arr = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’];
    const obj = {

    a: 1,
    b: 2,
    c: 3,
    d: 4
    }

for() 遍历数组元素

遍历值为数组元素索引

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

forEach() 遍历数组元素

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

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

map() 遍历数组元素

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

有返回值,返回一个新数组。

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

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

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

1.循环值为对象属性

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

2.值为数组索引

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

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

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

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

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

1.遍历值为数组元素

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

2.循环值为对象属性

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

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

总结

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

发表评论

表情:
评论列表 (有 0 条评论,156人围观)

还没有评论,来说两句吧...

相关阅读