JavaScript中的虚假值

描述 (Description)

A falsy value is something which evaluates to FALSE, for instance when checking a variable. There are only six falsey values in JavaScript: undefined, null, NaN, 0, "" (empty string), and false of course.

虚假值是评估为FALSE的值,例如在检查变量时。 JavaScript中只有6个falsey值: undefinednullNaN0"" (空字符串)和false

检查变量的虚假值 (Checking for falsy values on variables)

It is possible to check for a falsy value in a variable with a simple conditional:

可以使用简单的条件检查变量中的伪造值:

if (!variable) {
  // When the variable has a falsy value the condition is true.
}

一般范例 (General Examples)

var string = ""; // <-- falsy

var filledString = "some string in here"; // <-- truthy

var zero = 0; // <-- falsy

var numberGreaterThanZero // <-- truthy

var emptyArray = []; // <-- truthy, we'll explore more about this next

var emptyObject = {}; // <-- truthy

数组的乐趣 (Fun With Arrays)

if ([] == false) // <-- truthy, will run code in if-block

if ([]) // <-- truthy, will also run code in if-block

if ([] == true) // <-- falsy, will NOT run code in if-block

if (![]) // <-- falsy, will also NOT run code in if-block

警告 (Caveat)

Be aware of the data type when evaluating a value in a Boolean context. If the data type of the value is meant to be a number, the truthy/falsy evalution can result in an unexpected outcome:

在布尔上下文中评估值时,请注意数据类型。 如果值的数据类型应为数字 ,则正确/错误评估可能导致意外结果:

const match = { teamA: 0, teamB: 1 }
if (match.teamA)
  // The following won't run due to the falsy evaluation
  console.log('Team A: ' + match.teamA);
}

An alternative to the use case above is to evaluate the value using typeof:

上述用例的替代方法是使用typeof评估值:

const match = { teamA: 0, teamB: 1 }
if (typeof match.teamA === 'number')
  console.log('Team A: ' + match.teamA);
}

更多信息 (More Information)

翻译自: https://www.freecodecamp.org/news/falsy-values-in-javascript/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值