ES6中的for...in/of的使用
生活随笔
收集整理的這篇文章主要介紹了
ES6中的for...in/of的使用
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
ES6中for...in/of的使用
- 1、在數(shù)組中
- 2、在對象中
下面以對象和數(shù)組為例,介紹一下for…in,for…of以及基本for循環(huán)的使用
for…of: 遍歷的對象必須是可迭代的對象
可迭代的對象包括: Array,Set,Map,DOM中的NodeList對象,String對象,函數(shù)的arguments屬性
1、在數(shù)組中
ES5中的for循環(huán),正常遍歷中 i 指的是數(shù)組的下標
ES6中,for…in循環(huán),遍歷中的 i 指的是數(shù)組的下標
ES6中,for…of循環(huán),遍歷中的 i 指的是數(shù)組中的值
代碼展示:
let arr = [1, 3, 5, 7, 9]; for(let i = 0; i < arr.length; i++) {console.log('for循環(huán)中i是數(shù)組的下標:', i);console.log('arr[i]是數(shù)組中的值:', arr[i]); } console.log('----------------------------'); for(let i in arr) {console.log('for...in中i是數(shù)組的下標:', i); } console.log('----------------------------'); for(let i of arr) {console.log('for...of中i是數(shù)組中的值', i) }顯示效果:
2、在對象中
不能使用 for…of 遍歷對象,因為它不是一個可迭代的對象。
代碼展示:
let obj = {name: "YiBo",age: 18 } for(let i in obj) {console.log('for...in循環(huán)中的i值得是對象的鍵', i); } console.log('------------------------------------'); for(let i of obj) {console.log(i); }顯示效果:
總結(jié)
以上是生活随笔為你收集整理的ES6中的for...in/of的使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RGB图像转RGBA图像
- 下一篇: php表白树洞怎么写,树洞表白墙免费源码