JavaScript 的 truthy 和 falsy

truthy 和 falsy

JavaScript 里为 falsy 的值:

  1. false
  2. null
  3. undefined
  4. 0-0
  5. NaN
  6. '', "", ``(Empty template string 空模板字符串)
  7. document.all
  8. 0n: BigInt

所有的 JS 值非 truthy 即 falsy,所以,除了上述几种 falsy 值,其他的值全部为 truthy.

逻辑操作符 &&||

&&|| 的操作数可以是任意类型的表达式,返回值并不总是布尔值

"foo" && "bar"; // "bar"
"bar" && "foo"; // "foo"
"foo" && ""; // ""
"" && "foo"; // ""

33 && true; //   true
true && 33;  //  33
false && 33; //  false
33 && false;  //  false

33 || true; // 33
true || 33;  // true
false || 33; // 33
33 || false;  // 33

"foo" || "bar"; // "foo"
"bar" || "foo"; // "bar"
"foo" || ""; // "foo"
"" || "foo"; // "foo"

ifelse

以下的code,如果指定条件为 falsy, 执行 if 相关的语句,反之执行else相关的语句:

// false,0,undefined, null, "", '', NaN 等等
if (falsy值) {
	// 条件为falsy时执行的操作
} else {
	// 条件为truthy时执行的操作
}

例 1

let values = [1, 2, 3];

while (values.length) {
  console.log(values.pop());
}

例 2

let user = { isAdmin: true };

// ...

if (user && user.isAdmin) {
  // ...
}

[1] https://stackoverflow.com/questions/35642809/understanding-javascript-truthy-and-falsy

[2] https://mariusschulz.com/blog/the-and-and-or-operators-in-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值