我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?

我看到这件事的背景是,

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

当前回答

这个构造是将任何JavaScript表达式转换为它的布尔等价物。

例如:!!“他击落了我”==真的!!0===假。

其他回答

记住JavaScript中对true和false的求值很重要:

具有“价值”的一切都是真实的(即真实的),例如:101,3.1415,-11,“幸运的大脑”,新建对象()当然,这是真的没有“Value”的所有内容都是假的(即falsy),例如:0,-0,“”(空字符串),未定义,无效的NaN(不是数字)当然,也是假的

应用“逻辑非”运算符(!)计算操作数,将其转换为布尔值,然后对其求反。应用两次将对求反进行求反,从而有效地将值转换为布尔。不应用运算符将只是精确值的常规赋值。示例:

var value = 23; // number
var valueAsNegatedBoolean = !value; // boolean falsy (because 23 is truthy)
var valueAsBoolean = !!value; // boolean truthy
var copyOfValue = value; // number 23

var value2 = 0;
var value2AsNegatedBoolean = !value2; // boolean truthy (because 0 is falsy)
var value2AsBoolean = !!value2; // boolean falsy
var copyOfValue2 = value2; // number 0

value2=值;指定精确的对象值,即使它不是布尔值,因此value2不一定最终是布尔值。value2=!!价值作为操作数值的双重否定的结果,指定一个保证布尔值,它相当于以下内容,但要短得多,可读性强:

if(值){value2=真;}其他{value2=false;}

它将Object转换为布尔值。如果为假(例如,0、null、undefined等),则为假,否则为真。

!object  // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation

所以不是操作员;这只是!操作员两次。

这样做可能更简单:

Boolean(object) // Boolean

真实世界示例“测试IE版本”:

const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // Returns true or false

如果你⇒

console.log(navigator.userAgent.match(/MSIE 8.0/));
// Returns either an Array or null

但如果你⇒

console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// Returns either true or false

这是一种非常晦涩的类型转换方法。

! 表示不。所以真是假的,而且!假是真!0为真,并且!1为假。

所以你要将一个值转换成布尔值,将其反转,然后再次反转。

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

// Or just
val.enabled = Boolean(userId);

注意:由于!=运算符的作用以及哪些值被认为是正确的。

!!foo两次应用一元not运算符,并用于转换为布尔类型,类似于使用一元加号+foo转换为数字,并连接空字符串“”+foo以转换为字符串。

除了这些黑客,您还可以使用与基元类型相对应的构造函数(不使用new)来显式转换值,即。,

Boolean(foo) === !!foo
Number(foo)  === +foo
String(foo)  === ''+foo

它将所有的东西都强制为布尔值。

例如:

console.log(undefined);   // -> undefined
console.log(!undefined);  // -> true
console.log(!!undefined); // -> false

console.log('abc');   // -> abc
console.log(!'abc');  // -> false
console.log(!!'abc'); // -> true

console.log(0 === false);   // -> false
console.log(!0 === false);  // -> false
console.log(!!0 === false); // -> true