遍历时为什么只能用 [] 这种访问方式?

239 阅读1分钟
var xiaoming = {
    name: '小明',
    birth: 1990,
    school: 'No.1 Middle School',
    height: 1.70,
    weight: 65,
    score: null
};
for(var i in xiaoming){
    console.log(`${i}:${xiaoming[i]}`);
}

//会正常输出结果
name:小明
 birth:1990
 school:No.1 Middle School
 height:1.7
 weight:65
 score:null


如果是
for(var i in xiaoming){
    console.log(`${i}:${xiaoming.i}`);
}

//输出结果为
name:undefined
 birth:undefined
 school:undefined
 height:undefined
 weight:undefined
 score:undefined

之所以是这个结果,是因为前面的 i 会正常遍历对象的属性名,并输出。后面的 xiaoming.i 实际上是访问的 xiaoming 这个对象的 i 属性,因为没有所以才会输出 undefined。

如果给变量增加 i 这个属性,就会发现,输出结果会打印 7 遍 i 这个属性对应的值。