当前位置:首页 » 《休闲阅读》 » 正文

(js)for of 和 for in 的区别

19 人参与  2024年04月19日 12:25  分类 : 《休闲阅读》  评论

点击全文阅读


(js)for of 和 for in 的区别

总结:
for in适合遍历对象,
for of适合遍历数组。
for in遍历的是数组的索引,对象的属性,以及原型链上的属性。


1.循环数组

区别一:for in 和 for of 都可以循环数组。for in 输出的是数组的index下标,而for of 输出的是数组的每一项的值。

const arr = [1,2,3,4] // for ... infor (const key in arr){    console.log(key) // 输出 0,1,2,3    } // for ... offor (const key of arr){    console.log(key) // 输出 1,2,3,4    }

2.循环对象

区别二:for in 可以遍历对象,for of 不能,只能遍历带有iterator接口的,例如Set,Map,String,Array

const object = { name: 'lx', age: 23 }    // for ... in    for (const key in object) {      console.log(key) // 输出 name,age      console.log(object[key]) // 输出 lx,23    }     // for ... of    for (const key of object) {      console.log(key) // 报错 Uncaught TypeError: object is not iterable    }

3.数组对象

const list = [{ name: 'lx' }, { age: 23 }]  for (const val of list) {    console.log(val) // 输出{ name: 'lx' }, { age: 23 }    for (const key in val) {      console.log(val[key]) // 输出 lx,23    }  }

解决参考:https://blog.csdn.net/qq_43796489/article/details/119566594


点击全文阅读


本文链接:http://zhangshiyu.com/post/97528.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1