最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

理解JavaScript中的类型强制

IT培训 admin 3浏览 0评论

理解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运算符 - 并且只有在你将xfalse进行比较时才被强制执行: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运算符 - 并且只有在你将xfalse进行比较时才被强制执行: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)

  1. 暂无评论