1. 首页
  2. JS

今天写代码时,突然看到 “!!”运算符,一时竟然没反应过来,再来复习一下?

!!this.isVisit 是一种常见的 JavaScript 编程技巧,用于将 this.isVisit 的值强制转换为布尔类型(truefalse)。它的作用是通过双重逻辑非运算符(!!)确保结果是严格的布尔值。

详细解释

this.isVisit 是一个对象的属性,可能表示某个状态或标志(例如,用户是否访问过某个页面)。

它的值可能是 undefinednull0""falsetrue 或其他类型。

! 运算符的作用

第一个 ! 会将 this.isVisit 的值转换为布尔值并取反。

如果 this.isVisittruthy(如 true1"hello"),!this.isVisit 会返回 false

如果 this.isVisitfalsy(如 false0""nullundefined),!this.isVisit 会返回 true

!! 运算符的作用

第二个 ! 会将结果再次取反,从而得到原始的布尔值。

如果 this.isVisittruthy!!this.isVisit 会返回 true

如果 this.isVisitfalsy!!this.isVisit 会返回 false

const user = {
  isVisit: 1, // truthy 值
};

console.log(!!user.isVisit); // true

const guest = {
  isVisit: 0, // falsy 值
};

console.log(!!guest.isVisit); // false

使用场景

条件判断

确保条件表达式是严格的布尔值。

if (!!this.isVisit) {
  console.log("用户已访问");
} else {
  console.log("用户未访问");
}

状态初始化

将可能为 undefinednull 的值初始化为布尔值。

const hasVisited = !!this.isVisit;

API 返回值标准化

确保返回的布尔值不会被误解为其他类型。

function checkVisit() {
  return !!this.isVisit;
}

注意事项

如果 this.isVisit 已经是布尔值,!! 是多余的。

对于可能为 nullundefined 的值,!! 是一种简洁的默认值处理方式。

替代方案

如果需要更灵活的类型转换,可以使用 Boolean() 构造函数:

const hasVisited = Boolean(this.isVisit);

效果与 !!this.isVisit 相同,但可读性更高。

总结:!!this.isVisit 是一种快速将任意值转换为布尔值的技巧,适用于需要严格布尔值的场景。


TOP