理解JavaScript中的类型强制
我知道==
操作员执行类型强制。但我无法理解以下行为。
const x = new Boolean(false);
if (x) {
console.log("if(x) is true");
}
if (x == false) {
console.log("if(x == false) is true");
}
回答如下:
正如其他答案所提到的,那是因为x
是一个对象 - 一个布尔对象,但仍然是一个对象,因为你正在使用new
运算符 - 并且只有在你将x
与false
进行比较时才被强制执行:if (x)
正在检查x
是否是truthy值,因此不需要强制(没有涉及其他操作数):一个对象总是“真实”(weeeell ...几乎总是:typeof null
返回object
但它是一个虚假值。但这是另一个故事......)。
您可以轻松检查何时调用胁迫来点击toPrimitive符号:
var x = new Boolean(false);
// first of all, if it wasn't an object you couldn't
// do this
x[Symbol.toPrimitive] = function(hint) {
console.log({hint});
return this.valueOf();
}
// no console.log yet
if (x) {
console.log("if(x) is true");
}
// here you got the console.log before the one
// inside the block, since the coercion happens
// in the `if`
if (x == false) {
console.log("if(x == false) is true");
}
理解JavaScript中的类型强制
我知道==
操作员执行类型强制。但我无法理解以下行为。
const x = new Boolean(false);
if (x) {
console.log("if(x) is true");
}
if (x == false) {
console.log("if(x == false) is true");
}
回答如下:
正如其他答案所提到的,那是因为x
是一个对象 - 一个布尔对象,但仍然是一个对象,因为你正在使用new
运算符 - 并且只有在你将x
与false
进行比较时才被强制执行:if (x)
正在检查x
是否是truthy值,因此不需要强制(没有涉及其他操作数):一个对象总是“真实”(weeeell ...几乎总是:typeof null
返回object
但它是一个虚假值。但这是另一个故事......)。
您可以轻松检查何时调用胁迫来点击toPrimitive符号:
var x = new Boolean(false);
// first of all, if it wasn't an object you couldn't
// do this
x[Symbol.toPrimitive] = function(hint) {
console.log({hint});
return this.valueOf();
}
// no console.log yet
if (x) {
console.log("if(x) is true");
}
// here you got the console.log before the one
// inside the block, since the coercion happens
// in the `if`
if (x == false) {
console.log("if(x == false) is true");
}
与本文相关的文章
评论列表 (0)
- 暂无评论