javascript中点符号和括号表示法之间的区别 [英] difference between dot notation and bracket notation in javascript
问题描述
我试图理解 .Notation
和 []
表示法之间的区别。在我下面的问题中,当我使用 if(object [key] === true)
时,我得到了正确的答案。当我使用 if(object.key === true)
时,它不起作用。有人可以解释为什么会有所不同。
I am trying to understand the difference between .Notation
and []
notation. In my problem below when I use if (object[key] === true)
I get the correct answer. When I use if (object.key === true)
it does not work. Could someone explain why it's different.
var myObj = {
one: false,
two: false,
three: false,
four: true,
five: false,
six: false
};
var myFunc = function (object) {
for (var key in object) {
if (object[key] === true) {
return "There is a true value in this object";
} else {
}
}
return "Sorry, there are no true values in this object";
};
推荐答案
当您使用点表示法时, 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.
这篇关于javascript中点符号和括号表示法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!