Discuss
/
JavaScript
/
遍历时为什么只能用 [] 这种访问方式?
遍历时为什么只能用 [] 这种访问方式?
Topic sourcevar json = {
name: '小明',
birth: 1990,
school: 'No.1 Middle School',
height: 1.70,
weight: 65,
score: null
};
for (var j in json){
console.log(typeof(j)+"-"+j+":"+json[j]);
}
string-name:小明
string-birth:1990
string-school:No.1 Middle School
string-height:1.7
string-weight:65
string-score:null
经过使用typeof检测数据类型发现,从
var j in json
取出的j都是string类型的,所以只能用“[]”方式访问
var json = {
j: '小明',
birth: 1990,
school: 'No.1 Middle School',
height: 1.70,
weight: 65,
score: null
};
for (var j in json){
console.log(j+":"+json.j);
}
结果如下:
j:小明
VM1923:2 birth:小明
VM1923:2 school:小明
VM1923:2 height:小明
VM1923:2 weight:小明
VM1923:2 score:小明
所以这里的json.j是获取json的属性j的值,而非遍历json的所有属性
var json = { j: '小明', birth: 1990, school: 'No.1 Middle School', height: 1.70, weight: 65, score: null }; for (var j in json){ console.log(j+":"+json.j); }
结果如下:
j:小明 VM1923:2 birth:小明 VM1923:2 school:小明 VM1923:2 height:小明 VM1923:2 weight:小明 VM1923:2 score:小明
所以这里的json.j是获取json的属性j的值,而非遍历json的所有属性
清晰明了
- 1
顾顾顾北辰
之所以是这个结果,是因为前面的 i 会正常遍历对象的属性名,并输出。后面的 xiaoming.i 实际上是访问的 xiaoming 这个对象的 i 属性,因为没有所以才会输出 undefined。
如果给变量增加 i 这个属性,就会发现,输出结果会打印 7 遍 i 这个属性对应的值。
(留给跟我一样疑惑为什么遍历只能用 [] 访问的真小白)