使用!!操作符转换布尔值【Javascript】
时间:2019-08-25 发布者: 访问量:3398
使用!!操作符转换布尔值
有时候我们需要对一个变量查检其是否存在或者检查值是否有一个有效值,如果存在就返回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
在这个示例中,只要account.cash的值大于0,那么account.hasMoney返回的值就是true。
相关信息
用户评论
猜你喜欢
生活励志
生活文摘
生活福利
生活编程