原文: https://howtodoinjava.com/typescript/truthy-and-falsy/

在 JavaScript 中,真值是等于布尔值true的表达式,而假值则是等于布尔值false的表达式。 与其他语言不同,truefalse值不限于boolean数据类型和比较。 它可以具有许多其他形式。

让我们了解什么使 JavaScript 中的真假表达式成为事实。

假值

javascript 中共有 6 个假值/表达式。 我将使用此函数来检查值是真值还是假值。

  1. function testTruthyFalsy (val)
  2. {
  3. return val ? console.log('truthy') : console.log('falsy');
  4. }

布尔‘false

显然布尔值falsefalse

  1. testTruthyFalsy (false); //Prints 'falsy'

空字符串,即''

任何空字符串都将被求值为false

  1. testTruthyFalsy (''); //Prints 'falsy'

undefined

任何undefined变量将等于false

  1. var my_var = undefined;
  2. testTruthyFalsy (my_var); //Prints 'falsy'

null

任何null变量将等于false

  1. var my_var = null;
  2. testTruthyFalsy (my_var); //Prints 'falsy'

NaN

结果为NaN(不是数字)的任何数值表达式都将等于false

  1. testTruthyFalsy (NaN); //Prints 'falsy'

数字零,即 +0 或 -0

任何结果为零(+0-0)的数值表达式都将等于false

  1. testTruthyFalsy ( 2 - 2 ); //Prints 'falsy'
  2. testTruthyFalsy ( 0 ); //Prints 'falsy'

真值

除了上面列出的假值以外的任何表达式或值 - 被认为是真值。 例如:

  1. function testTruthyFalsy (val)
  2. {
  3. return val ? console.log('truthy') : console.log('falsy');
  4. }
  5. testTruthy(true); // truthy
  6. testTruthy(false); // falsy
  7. testTruthy(new Boolean(false)); // truthy (object is always true)
  8. testTruthy(''); // falsy
  9. testTruthy('Packt'); // truthy
  10. testTruthy(new String('')); // true (object is always true)
  11. testTruthy(1); // truthy
  12. testTruthy(-1); // truthy
  13. testTruthy(NaN); // falsy
  14. testTruthy(new Number(NaN)); // truthy (object is always true)
  15. testTruthy({}); // truthy (object is always true)
  16. var obj = { name: 'John' };
  17. testTruthy(obj); // truthy
  18. testTruthy(obj.name); // truthy

将我的问题放在评论部分。

学习愉快!