JavaScript 中的真值和假值

JavaScript 中的真值和假值

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

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

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

假值

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

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

布尔‘false

显然布尔值falsefalse

			testTruthyFalsy (false);	//Prints 'falsy'

空字符串,即''

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

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

undefined

任何undefined变量将等于false

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

null

任何null变量将等于false

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

NaN

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

			testTruthyFalsy (NaN);		//Prints 'falsy'

数字零,即 +0 或 -0

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

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

真值

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

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

testTruthy(true); 					// truthy 
testTruthy(false); 					// falsy 
testTruthy(new Boolean(false)); 	// truthy (object is always true) 

testTruthy(''); 					// falsy 
testTruthy('Packt'); 				// truthy 
testTruthy(new String('')); 		// true (object is always true) 

testTruthy(1); 						// truthy 
testTruthy(-1); 					// truthy 
testTruthy(NaN); 					// falsy 
testTruthy(new Number(NaN)); 		// truthy (object is always true) 

testTruthy({}); 					// truthy (object is always true) 

var obj = { name: 'John' }; 
testTruthy(obj); 					// truthy 
testTruthy(obj.name); 				// truthy 

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

学习愉快!