我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
!!foo两次应用一元not运算符,并用于转换为布尔类型,类似于使用一元加号+foo转换为数字,并连接空字符串“”+foo以转换为字符串。
除了这些黑客,您还可以使用与基元类型相对应的构造函数(不使用new)来显式转换值,即。,
Boolean(foo) === !!foo
Number(foo) === +foo
String(foo) === ''+foo
其他回答
它将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
只是为了检查是否存在
if(!!isComplianceOnHold){
//write code here is not undefined
//if isComplianceOnHold is undefined or null will not enter in net is false
// if isComplianceOnHold is not null or even boolean net result is true and enter inside if block
}
任何值未定义或为null的对象,包括值为false的布尔对象,在传递给条件语句时其计算结果为true
这只是逻辑NOT运算符,两次。它用于将某些内容转换为布尔值,例如:
true === !!10
false === !!0
这是检查未定义、“未定义”、null、“null”、“”
if (!!var1 && !!var2 && !!var3 && !!var4 ){
//... some code here
}
a = 1;
alert(!a) // -> false : a is not not defined
alert(!!a) // -> true : a is not not defined
对于a、 它检查a是否未定义,而!!a检查变量是否已定义。
!!a与相同!(!a)。如果定义了a,则a为真!a是假的,而且!!a为真。