for in 和 for of 的区别
生活随笔
收集整理的這篇文章主要介紹了
for in 和 for of 的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、for...in 循環:只能獲得對象的鍵名,不能獲得鍵值
? ? ? for...of 循環:允許遍歷獲得鍵值
var arr = ['red', 'green', 'blue']for(let item in arr) {console.log('for in item', item)}/*for in item 0for in item 1for in item 2*/for(let item of arr) {console.log('for of item', item)}/*for of item redfor of item greenfor of item blue*/?
2、對于普通對象,沒有部署原生的 iterator 接口,直接使用?for...of 會報錯
var obj = {'name': 'Jim Green','age': 12}for(let key of obj) {console.log('for of obj', key)}// Uncaught TypeError: obj is not iterable可以使用?for...in 循環遍歷鍵名
for(let key in obj) {console.log('for in key', key)}/*for in key namefor in key age*/也可以使用 Object.keys(obj) 方法將對象的鍵名生成一個數組,然后遍歷這個數組
for(let key of Object.keys(obj)) {console.log('key', key)}/*key namekey age*/?
3、for...in 循環不僅遍歷數字鍵名,還會遍歷手動添加的其它鍵,甚至包括原型鏈上的鍵。for...of 則不會這樣
let arr = [1, 2, 3]arr.set = 'world' // 手動添加的鍵Array.prototype.name = 'hello' // 原型鏈上的鍵for(let item in arr) {console.log('item', item)}/*item 0item 1item 2item setitem name*/for(let value of arr) {console.log('value', value)}/*value 1value 2value 3*/?
4、forEach 循環無法中途跳出,break 命令或 return 命令都不能奏效
let arr = [1, 2, 3, 5, 9]arr.forEach(item => {if(item % 2 === 0) {return}console.log('item', item)})/*item 1item 3item 5item 9*/for...of 循環可以與break、continue 和 return 配合使用,跳出循環
for(let item of arr) {if(item % 2 === 0) {break}console.log('item', item)}// item 1?
5、無論是 for...in 還是 for...of 都不能遍歷出 Symbol 類型的值,遍歷 Symbol 類型的值需要用 Object.getOwnPropertySymbols() 方法
{let a = Symbol('a')let b = Symbol('b')let obj = {[a]: 'hello',[b]: 'world',c: 'es6',d: 'dom'}for(let key in obj) {console.info(key + ' --> ' + obj[key])}/*c --> es6d --> dom*/let objSymbols = Object.getOwnPropertySymbols(obj)console.info(objSymbols) // ?[Symbol(a), Symbol(b)]objSymbols.forEach(item => {console.info(item.toString() + ' --> ' + obj[item])})/*Symbol(a) --> helloSymbol(b) --> world*/// Reflect.ownKeys 方法可以返回所有類型的鍵名,包括常規鍵名和Symbol鍵名let keyArray = Reflect.ownKeys(obj)console.log(keyArray) // ?["c", "d", Symbol(a), Symbol(b)] }?
總之,for...in 循環主要是為了遍歷對象而生,不適用于遍歷數組
for...of 循環可以用來遍歷數組、類數組對象,字符串、Set、Map 以及 Generator 對象
轉載于:https://www.cnblogs.com/rogerwu/p/10738776.html
總結
以上是生活随笔為你收集整理的for in 和 for of 的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BZOJ 3669 魔法森林
- 下一篇: 我在大学毕业后学习Linux、pytho