描述 (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值: undefined
, null
, NaN
, 0
, ""
(空字符串)和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/