我知道在JavaScript中你可以这样做:
var oneOrTheOther = someOtherVar || "these are not the droids you are looking for...";
Run Code Online (Sandbox Code Playgroud)
其中变量oneOrTheOther将在第一表达式的值,如果它不是null,undefined或false.在这种情况下,它被分配给第二个语句的值.
但是,oneOrTheOther当我们使用逻辑AND运算符时,变量会分配给什么?
var oneOrTheOther = someOtherVar && "some string";
Run Code Online (Sandbox Code Playgroud)
什么时候会发生someOtherVar非假的?假的
时候会发生什么someOtherVar?
只是学习JavaScript,我很好奇与AND运算符一起分配会发生什么.
javascript variable-assignment logical-operators and-operator
使用node.js控制台(节点0.10.24)
> var x = (undefined && true);
undefined
> x;
undefined
> x = (true && undefined);
undefined
> x;
undefined
Run Code Online (Sandbox Code Playgroud)
为什么比较返回未定义?我希望它返回false,因为undefined被认为是"假的".
我一直在阅读有关JavaScript吊装的消息.
Ben Cherry的JavaScript范围和吊装
Dmitry Soshnikov关于"吊装"的两个词
而且,更多关于JavaScript类型强制,真假测试: 真理,平等和JavaScript以及其他一些资源
在练习一些时,发现我遗漏了一些关于吊装的重要概念和一个变量'truthy&falsy.
var foo = 1;
function bar() {
if (!foo) {
alert('inside if');
var foo = 10;
}
}
bar();
Run Code Online (Sandbox Code Playgroud)
O/P: inside if
怀疑: 'foo'值为'1',if(!foo)应该评估false并且不应该执行该块(引用来自上面的资源:提升仅影响var&function声明,但不影响执行).但为什么会显示该警报.如果我直接使用就不是这种情况false(如下面的no-tricks代码所示:代码片段#3)
var foo = 1;
function bar() {
if (!foo) {
alert('inside if');
}
}
bar();
Run Code Online (Sandbox Code Playgroud)
o/p:没有输出; 意味着控制没有进入'如果'块
这是人们可以期待的
var foo = 1;
function bar() {
if (false) {
alert('inside if');
var foo = …Run Code Online (Sandbox Code Playgroud)