javascript逻辑分配如何工作? [英] How does javascript logical assignment work?
问题描述
在javascript中,如果我们有一些代码,例如
var a =one;
var b = q ||一个;
alert(b);
逻辑OR运算符将为b分配值,警报将为1。 / p>
这仅限于作业,还是我们可以在任何地方使用它?
似乎空字符串被视为与undefined相同。这是对吗?
这如何与AND变量一起使用?它们的组合怎么样?
什么时候使用这些习语,或什么时候不用?
对于 q || a
评估为 a
, q
应为'falsy'值。你做的是短路评估。
回答你的问题:
-
逻辑运算符(如和 -
&&
或 -||
)可以是也用于其他情况。更常见的是条件语句,如if
。 此处更多内容 -
空字符串不被视为
undefined
。两者都是虚假的价值观。还有一些虚假的价值观。 更多信息 -
<$ JavaScript中的c $ c> AND 或
&&
不是变量。这是一个运营商 -
你使用的习惯用法很常见。
var x = val || '默认'; //通常是
的替代
var x = val? val:'default'//或
if(val)
var x = val;
else
var x ='default';
In javascript, if we have some code such as
var a = "one";
var b = q || a;
alert (b);
The logical OR operator will assign a's value to b, and the alert will be "one."
Is this limited to assignments only or can we use it everywhere?
It seems an empty string is treated the same as undefined. Is this right?
How does this work with AND variables? What about combinations of them?
What is a good example of when to use these idioms, or when not to?
For your q || a
to evaluate to a
, q
should be a 'falsy' value. What you did is called "Short circuit evaluation".
Answering your questions:
The logical operators (like and -
&&
, or -||
) can be used in other situations too. More generally in conditional statements likeif
. More hereEmpty string is not treated as
undefined
. Both are falsy values. There are a few more falsy values. More hereAND
, or&&
in JavaScript, is not a variable. It is an operatorThe idiom you have used is quite common.
var x = val || 'default'; //is generally a replacement for
var x = val ? val : 'default' //or
if (val) var x = val; else var x = 'default';
这篇关于javascript逻辑分配如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!