布尔文本和布尔值之间有什么区别? [英] What's the difference between a boolean literal and a boolean value?

查看:876
本文介绍了布尔文本和布尔值之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎没有找到一个清楚的解释,这两者之间的区别是什么。我也想指出,我也不真正理解文字和值之间的区别。



Do boolean literals使用布尔对象吗?

解决方案

A literal 是你脚本中提供的值,因此它们是固定的。



A 是一条数据。因此,字面值是一个值,但不是所有的值都是文字。



示例:

 code> 1; // 1是字面值
var x = 2; // x取文字2的值
x = x + 3; //将文字3的值添加到x。 x现在的值为5,但5不是文字。

对于问题的第二部分,您需要知道原始是。它比这个有点复杂,但你可以将它们视为不是一个对象的所有类型。 Javascript有5个,包括 boolean number 。所以这些通常不是一个对象。



为什么你仍然可以(152).toString()在Javascript中?这是因为一种称为强制(在其他语言也称为自动装箱)的机制。当需要时,Javascript引擎将在原语及其对象包装器之间进行转换。 boolean Boolean 以下是对Javascript基元和自动装箱的完美解释



不是这种行为并不是你期望的,特别是 Boolean p>

示例:

  true; //这是一个布尔原语
new Boolean(true); //这导致一个对象,但是字面值true仍然是一个原始的
(true).toString(); //将文本true转换为布尔对象,并将其toString方法调用
if(new Boolean(false)){alert('Eh?'); }; //将警告,因为不为null或未定义的每个布尔对象评估为真(因为它存在)


I can't seem to find a clear explanation as to what the difference is between these two. I'd also like to point out that I don't really understand the difference between literals and values either.

Do boolean literals use the Boolean object?

解决方案

A literal is a value you literally provide in your script, so they are fixed.

A value is "a piece of data". So a literal is a value, but not all values are literals.

Example:

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.

For your second part of the question you need to know what a primitive is. It's a little more complicated than this, but you can view them as "all types that aren't an object". Javascript has 5 of those, including boolean and number. So those aren't usually an object.

Why then can you still do (152).toString() in Javascript? This is because of a mechanism called Coercion (in other languages also called auto-boxing). When required the Javascript engine will convert between a primitive and its object wrapper, e.g. boolean and Boolean. Here is an excellent explanation of Javascript primitives and auto-boxing.

Not that this behaviour isn't really what you'd expect sometimes, especially with Boolean

Example:

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)

这篇关于布尔文本和布尔值之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆