今天,当我发现一些奇怪的东西时,我在我的应用程序中使用JavaScript代码.
var someVar = 25;
var anotherVar = 50;
var out = (anotherVar == 50 && someVar);
console.log(out) // outputs 25 and not true or false;
Run Code Online (Sandbox Code Playgroud)
知道发生了什么事吗?
我在以下代码中遇到过Mithril.js:
finish(state == 1 && 3)
Run Code Online (Sandbox Code Playgroud)
对于我的(Java/C程序员)来说,它看起来应该总是调用,finish(true)如果state是1,finish(false)如果state不是1.但它实际上似乎是finish(3)针对前者和finish(false)后者.
这背后的逻辑是什么?
这是JavaScript中的惯用语,还是一个坏主意?对我而言,这是非常模糊的.
我在我们的应用程序中遇到了这段代码(已修改),并对它的工作方式感到困惑:
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);
}
Run Code Online (Sandbox Code Playgroud)
当你调用test()函数时,文字"嗯?" 警报.我不确定getValue的结果是如何返回的,我会认为做A && B && C && D会返回true,而不是D的值.
javascript ×3