将javascript对象加在一起 [英] ANDing javascript objects together

查看:59
本文介绍了将javascript对象加在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我们的应用程序中遇到了这段代码(已修改),并对它是如何工作感到困惑:

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);
    }

当你调用test()函数时,文字嗯?警报。我不确定getValue的结果是如何返回的,我会认为做A&& B&& C&& D会返回true,而不是D的值。

when you call the test() function, the text "Huh?" 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.

推荐答案

这是因为布尔运算符可以返回一个操作数,而不一定是 Boolean 结果,例如:

That happens because the Boolean Operators in JavaScript can return an operand, and not necessarily a Boolean result, e.g.:

Logical AND运算符(&& )将返回值第二个操作数的第一个是 truthy

The Logical AND operator (&&), will return the value of the second operand if the first is truthy:

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

如果是第一个操作数,它将返回第一个操作数的值 falsy

And it will return the value of the first operand if it is by itself falsy:

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

这就是为什么在你的例子中嗯?,因为前面的所有表达式都是 truthy

That's why in your example "Huh?" is returned, because all the preceding expressions are truthy:

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






Logical OR运算符( || )有类似的行为,它将返回第二个操作数的值,如果第一个是 falsy


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"

并且它将返回第一个操作数的值,如果它本身不是-falsy:

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";
}

注意: Falsy值是那些强制到的值 false 在布尔上下文中使用时,它们是: null undefined NaN 0 ,零长度字符串,当然还有 false 。其他任何东西都会强制到 true

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. Anything else will coerce to true.

这篇关于将javascript对象加在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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