将javascript对象加在一起

编程入门 行业动态 更新时间:2024-10-27 20:39:47
本文介绍了将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对象加在一起

本文发布于:2023-10-19 20:34:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1508695.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:加在   对象   javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!