更新时间:2022-12-28 18:33:50
当您使用点表示法时, key
表示对象中的实际属性,不在那里。因此,返回 undefined
,它不等于 true
。
When you use dot notation, key
means the actual property in the object, which will not be there. So, undefined
is returned which is not equal to true
.
当您使用 []
表示法时,您正在访问对象中的属性,其名称在变量 key
中。所以,这将有效。
When you use []
notation you are accessing the property in the object with the name in the variable key
. So, that will work.
例如,
var myObj = {
myVar : 1
};
for (var key in myObj) {
console.log(key);
console.log(myObj.key);
console.log(myObj[key]);
}
这将打印,
myVar
undefined
1
因为, myObj
没有名为 key
的成员( myObj.key
尝试获取名为 key
的成员,在下一种情况下, myObj
有一个名为的成员 myVar
( myObj [key]
尝试使用键中的值获取成员
)。
Because, myObj
has no member named key
(myObj.key
tries to get the member with the name key
) and in the next case, myObj
has a member named myVar
(myObj[key]
tries to get the member with the value in key
).
点符号
[]符号
这提供了灵活性。您可以使用变量动态访问成员。
This offers flexibility. You can dynamically access the members with a variable.