布尔文字和布尔值之间有什么区别?

时间:2013-05-01 22:26:25

标签: javascript compiler-construction computer-science

我似乎无法清楚地解释这两者之间的区别。我还想指出,我也不太了解文字和价值观之间的区别。

布尔文字是否使用布尔对象?

3 个答案:

答案 0 :(得分:14)

literal是您字面上在脚本中提供的值,因此它们已修复。

value是“一段数据”。所以文字是一个值,但并非所有的值都是文字。

示例:

1; // 1 is a literal
var x = 2; // x takes the value of the literal 2
x = x + 3; // Adds the value of the literal 3 to x. x now has the value 5, but 5 is not a literal.

对于问题的第二部分,您需要知道a primitive是什么。它比这复杂一点,但您可以将它们视为“所有不是对象的类型”。 Javascript有5个,包括booleannumber。所以那些通常不是一个对象。

为什么你仍然可以在Javascript中(152).toString()?这是因为一种称为强制的机制(在其他语言中也称为自动装箱)。当需要时,Javascript引擎将在基元和其对象包装器之间进行转换,例如, booleanBooleanHere is an excellent explanation of Javascript primitives and auto-boxing

并不是说这种行为有时并不是您所期望的,尤其是Boolean

示例:

true; // this is a `boolean` primitive
new Boolean(true); // This results in an object, but the literal `true` is still a primitive
(true).toString(); // The literal true is converted into a Boolean object and its toString method is called
if(new Boolean(false)) { alert('Eh?'); }; // Will alert, as every Boolean object that isn't null or undefined evaluates to true (since it exists)

答案 1 :(得分:0)

Values是无法再评估的表达式。这意味着,这些是价值观:

  • X
  • 123
  • “asdqwe”

现在,literals是固定值表达式。从上面的列表中,以下是文字:

  • 123
  • “asdqwe”

因此,x有一个值但不是固定的。

回答主要问题,布尔值只能有两个文字:falsetrue,每个布尔变量都是一个布尔值。

你会在大学的编译器或计算机语义课程中看到这个,但如果你仍然不理解其中的差异,那么这里链接的维基百科页面非常好。

答案 2 :(得分:0)

比较!!xBoolean(x)new Boolean(x).valueOf()

的值
[true, false, null, undefined, 1, 0, NaN, Infinity, "true", "false", "", [], {}, new Boolean(false)]
.forEach(e => console.debug(
   [ !!e, Boolean(e), (new Boolean(e)).valueOf() ], e
))

// !!e, Boolean, valueOf
[true,  true,    true]   true
[false, false,   false]  false
[false, false,   false]  null
[false, false,   false]  undefined
[true,  true,    true]   1
[false, false,   false]  0
[false, false,   false]  NaN
[true,  true,    true]   Infinity
[true,  true,    true]   "true"
[true,  true,    true]   "false"
[false, false,   false]  ""
[true,  true,    true]   []
[true,  true,    true]   Object {}
[true,  true,    true]   Boolean {[[PrimitiveValue]]: false} // new Boolean(false)

注意:

Boolean(x) === !!x

typeof true == "boolean"
typeof Boolean(x) == "boolean"
typeof new Boolean(x) == "object" // not boolean!
typeof Boolean == "function"

Boolean(new Boolean(false)) == true // <- any object converted to boolean is true!
Boolean(new Boolean(false).valueOf()) == false