1、使用 !!操作符转换布尔值 有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回 true 值。为了做这样的验证,我们可以使用 !! 操作符来实现是非常的方便与简单。对于变量可以使用 !!variable 做检测,只要变量的值为:0、null、" "、undefined 或者NaN 都将返回的是 false,反之返回的是 true。比如下面的示例: function Account(cash) { this.cash = cash; this.hasMoney = !!cash; } var account = new Account(100.50); console.log(account.cash); // 100.50 console.log(account.hasMoney); // true var emptyAccount = new Account(0); console.log(emptyAccount.cash); // 0 console.log(emptyAccount.hasMoney); // false 在这个示例中,只要 2、使用
|
|
声明:文章版权归原作者所有 部分文章转自互联网 如有侵权请联系
[邮箱地址] 删除
|