空白字符串在JavaScript中是true还是false?

时间:2018-07-28 15:55:26

标签: javascript

'' == false // true
' ' == false // true
if ('') {
  // this code is not run
}
if (' ') {
  // this code is run
}

如您所见,有有趣的结果。 如我们所知,空字符串被视为falsy。 但是,视情况而定,将空白字符串视为truthyfalsy

2 个答案:

答案 0 :(得分:0)

您可以在问题中看到有关toBoolean行为的链接。另一个有趣的花絮; javascript还有另一个比较运算符===,用于检查值和类型

'' == false // true
'' === false // false

答案 1 :(得分:0)

空白字符串为false。

# vtk DataFile Version 4.2
vtk output
ASCII
DATASET POLYDATA
POINTS 4 float
0 0 0 1 0 0 2 0 0 
3 0 0 
LINES 1 6
5 0 1 2 3 0 # This line has 5 points and last and first point are the same (0)

这通常是console.log(' '==true); console.log(''==true);运算符的问题;它试图使要比较的对象类型相等。如果您使用==运算符,它将不会尝试强制输入。

===

相关问题