简体   繁体   English

将 javascript 对象 ANDing 在一起

[英]ANDing javascript objects together

I ran across this chunk of code (modified) in our application, and am confused to how it works:我在我们的应用程序中遇到了这段代码(已修改),并且对它的工作方式感到困惑:

    function someObject()
    {
        this.someProperty = {};
        this.foo = 
        {
            bar:
            {
                baz: function() { return "Huh?" }
            }
        };

        this.getValue = function()
        {
            return (this.someProperty && this.foo.bar && this.foo.bar.baz && this.foo.bar.baz()) || null;
        }
    }

    function test()
    {
        var o = new someObject();
        var val = o.getValue();
        alert(val);
    }

when you call the test() function, the text "Huh?"当你调用 test() 函数时,文本“嗯?” is alerted.被警告。 I'm not sure how the result of getValue is returning that, I would've thought doing A && B && C && D would have returned true, rather than the value of D.我不确定 getValue 的结果是如何返回的,我本以为执行 A && B && C && D 会返回 true,而不是 D 的值。

That happens because the Boolean Operators in JavaScript can return an operand, and not necessarily a Boolean result, eg:发生这种情况是因为 JavaScript 中的布尔运算符可以返回一个操作数,而不一定是一个Boolean结果,例如:

The Logical AND operator ( && ), will return the value of the second operand if the first is truthy :如果第一个操作数为,则逻辑与运算符 ( && ) 将返回第二个操作数的值:

true && "foo"; // "foo"

And it will return the value of the first operand if it is by itself falsy :如果它本身是假的,它将返回第一个操作数的值:

NaN && "anything"; // NaN
0 && "anything";   // 0

That's why in your example "Huh?"这就是为什么在你的例子中"Huh?" is returned, because all the preceding expressions are truthy :被返回,因为所有前面的表达式都是真的

alert("A" && "B" && "C" && "Huh?"); // "Huh?"
alert(true && true && true && "Huh?"); // "Huh?"

The Logical OR operator ( || ) has a similar behavior, it will return the value of the second operand, if the first one is falsy :逻辑或运算符 ( || ) 具有类似的行为,如果第一个操作数为,它将返回第二个操作数的值:

false || "bar"; // "bar"

And it will return the value of the first operand if it is by itself non-falsy:如果它本身是非假的,它将返回第一个操作数的值:

"foo" || "anything"; // "foo"

This behavior is often used to set default values , for example:此行为通常用于设置默认值,例如:

function test (arg1) {
  arg1 = arg1 || "default value";
}

Note: Falsy values are those that coerce to false when used in a boolean context, and they are: null , undefined , NaN , 0 , zero-length string, and of course false .注意:假值是在布尔上下文中使用时强制为false的值,它们是: nullundefinedNaN0 、零长度字符串,当然还有false Anything else will coerce to true .其他任何东西都将强制为true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM