javascript字符串如何转布尔值

xiaoxiao2026-03-16  3

问题脚本

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;

 

转载请注明原文地址: https://www.6miu.com/read-5046012.html

最新回复(0)