javascript中点符号和括号符号的区别 [英] difference between dot notation and bracket notation in javascript

查看:12
本文介绍了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 的成员)code>) 并且在下一种情况下,myObj 有一个名为 myVar 的成员(myObj[key] 尝试获取具有以下值的成员)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).

点符号

jslint 更喜欢点表示法.

[] 符号

这提供了灵活性.您可以使用变量动态访问成员.

This offers flexibility. You can dynamically access the members with a variable.

这篇关于javascript中点符号和括号符号的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆