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

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

Topic source
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 这个属性对应的值。

(留给跟我一样疑惑为什么遍历只能用 [] 访问的真小白)

小宋是呢

#2 Created at ... [Delete] [Delete and Lock User]
var 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类型的,所以只能用“[]”方式访问

留白A_Z

#3 Created at ... [Delete] [Delete and Lock User]
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的所有属性

不羁的00

#4 Created at ... [Delete] [Delete and Lock User]
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的所有属性

清晰明了

10天写出来的语言能用就行。。。。还要什么自行车:)


  • 1

Reply