for...in
循环主要是为了遍历对象而生,不适用于遍历数组for...of
循环可以用来遍历数组、类数组对象,字符串、Set、Map 以及 Generator 对象
一:数组
of是输出value, in输出的是索引index
function test(){
let a=['red','green','yellow','bank']
let ofArr = []
let inArr = []
for(let i of a){
ofArr.push(i)
}
for(let j in a){
inArr.push(j)
}
console.log(ofArr) // ["red", "green", "yellow", "bank"]
console.log(inArr) // ["0", "1", "2", "3"]
}
二维数组
function test(){
let a = [{key:'red', value:1}, {key:'green', value:2}, {key:'yellow', value:3}, {key:'bank', value:4}]
let ofArr = []
let inArr = []
for(let i of a){
ofArr.push(i)
}
for(let j in a){
inArr.push(j)
}
console.log(ofArr)
console.log(inArr)
}
输出:
image.png
二:对象
for...of循环对象时会报错
function test(){
let a = {key:'red', value:1}
let ofArr = []
let inArr = []
for(let i of a){ // 报错
ofArr.push(i)
}
for(let j in a){
inArr.push(j)
}
console.log(ofArr) // 报错
console.log(inArr) // ["key", "value"]
}
test()
三:
无论是 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 --> es6
d --> dom
*/
let objSymbols = Object.getOwnPropertySymbols(obj)
console.info(objSymbols) // [Symbol(a), Symbol(b)]
objSymbols.forEach(item => {
console.info(item.toString() + ' --> ' + obj[item])
})
/*
Symbol(a) --> hello
Symbol(b) --> world
*/
// Reflect.ownKeys 方法可以返回所有类型的键名,包括常规键名和Symbol键名
let keyArray = Reflect.ownKeys(obj)
console.log(keyArray) // ["c", "d", Symbol(a), Symbol(b)]
网友评论