`
jspine
  • 浏览: 101968 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

javascript字符串如何转布尔值

阅读更多

问题脚本

var str = 'false';
if(str){
    alert('正确');
}else{
    alert('false');
}
 

运行上面的脚本你会发现str不管是“true”还是“false”,都会跳出“正确”提示框。(看来这javascript弱类型还是有类型啊。)

官方说明:

Note: If the value parameter is omitted, or is 0, -0, null, "", false, undefined, or NaN, the object is set to false. Otherwise it is set to true (even with the string "false")!

主要是Boolean的构造函数对于字符串只要不为空都为"true";

解决方法:

 

var str = 'false';
if(str ==='true'){
    alert('正确');
}else{
    alert('false');
}

 这样除了true之外,其他都是false;

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics