我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
!! 不是运算符。这只是!操作员两次。
但使用JavaScript,应用!!在大多数情况下,将Object转换为Boolean是冗余和冗长的,因为:
值未定义或为空的任何对象,包括值为false的布尔对象,传递给有条件的陈述
示例:if({}){console.log(“{}是true”)}//logs:“{}是true”
其他回答
它将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
有时,有必要检查函数中是否有值,数量本身对我们来说并不重要,但它是否重要。
例如,我们想检查用户是否有专业,并且我们有一个如下的功能:
hasMajor() {return this.major} // It returns "(users major is) Science"
但答案对我们来说并不重要。我们只想检查它是否有主,我们需要一个布尔值(true或false)。我们如何得到它?
就像这样:
hasMajor() { return !(!this.major)}
或相同
hasMajor() {return !!this.major)}
如果this.major有值,那么!this.major返回false,但因为值有出口,我们需要返回true,所以我们使用!两次返回正确答案!(!this.major)。
这只是逻辑NOT运算符,两次。它用于将某些内容转换为布尔值,例如:
true === !!10
false === !!0
!!expr(后跟表达式的两个!运算符)根据表达式的真实性返回布尔值(true或false)。当用于非布尔类型时,它更有意义。考虑以下示例,尤其是第三个示例及其后续示例:
!!false === false
!!true === true
!!0 === false
!!parseInt("foo") === false // NaN is falsy
!!1 === true
!!-1 === true // -1 is truthy
!!(1/0) === true // Infinity is truthy
!!"" === false // empty string is falsy
!!"foo" === true // non-empty string is truthy
!!"false" === true // ...even if it contains a falsy value
!!window.foo === false // undefined value is falsy
!!undefined === false // undefined primitive is falsy
!!null === false // null is falsy
!!{} === true // an (empty) object is truthy
!![] === true // an (empty) array is truthy; PHP programmers beware!
它将后缀转换为布尔值。