我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
我看到一些代码似乎使用了我不认识的运算符,以两个感叹号的形式,像这样:!!。有人能告诉我这个接线员做什么吗?
我看到这件事的背景是,
this.vertical = vertical !== undefined ? !!vertical : this.vertical;
当前回答
我认为值得一提的是,与逻辑“与/或”组合的条件不会返回布尔值,而是在&&的情况下返回最后一次成功或第一次失败,在条件链的||的情况下,返回第一次成功或最后一次失败。
res = (1 && 2); // res is 2
res = (true && alert) // res is function alert()
res = ('foo' || alert) // res is 'foo'
为了将条件转换为真正的布尔文字,我们可以使用双重否定:
res = !!(1 && 2); // res is true
res = !!(true && alert) // res is true
res = !!('foo' || alert) // res is true
其他回答
它将后缀转换为布尔值。
它模拟Boolean()转换函数的行为。无论给定什么操作数,第一个NOT都返回布尔值。第二个NOT否定该布尔值,从而给出变量的真正布尔值。最终结果与对值使用Boolean()函数相同。
我只是想补充一下
if(variableThing){
// do something
}
与
if(!!variableThing){
// do something
}
但当某些东西未定义时,这可能是一个问题。
// a === undefined, b is an empty object (eg. b.asdf === undefined)
var a, b = {};
// Both of these give error a.foo is not defined etc.
// you'd see the same behavior for !!a.foo and !!b.foo.bar
a.foo
b.foo.bar
// This works -- these return undefined
a && a.foo
b.foo && b.foo.bar
b && b.foo && b.foo.bar
这里的技巧是,&&s链将返回它找到的第一个假值,这可以被馈送到if语句等。因此,如果b.foo未定义,它将返回undefined并跳过b.foo.bar语句,我们不会得到任何错误。
上面的返回未定义,但如果您有一个空字符串,false,null,0,undefined,这些值将返回,一旦我们在链中遇到它们——[]和{}都是“truthy”,我们将沿着所谓的“&&链”继续到右边的下一个值。
P.S.执行上述(b&&b.foo)的另一种方法是(b||{}).foo。这些方法是等效的,因为如果b未定义,则b||{}将为{},并且您将访问空对象中的值(无错误),而不是尝试访问“undefined”中的值。
因此,(b||{}).foo与b&&b.foo相同,((b||{})/foo||{}).bar与b&&b.foo&&b.foo.bar相同。
只是为了检查是否存在
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
有时,有必要检查函数中是否有值,数量本身对我们来说并不重要,但它是否重要。
例如,我们想检查用户是否有专业,并且我们有一个如下的功能:
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)。