08.转换为Boolean.html 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <script>
  9. /*
  10. 将其他的数据类型转换为Boolean
  11. 方法一:
  12. -使用Boolean()函数
  13. 数字-->布尔
  14. -除了0和NaN,其余的都是true
  15. 字符串-->布尔
  16. -除了空串,其余的都是true
  17. null和undefined都会转换为false
  18. 对象也会转换为true
  19. 方法二:
  20. 对任意的数据类型做两次非运算,即可将其转换为布尔值
  21. 例:var a = "hello";
  22. a = !!a;//结果为true
  23. */
  24. var a = 123;//true
  25. a=-123;//true
  26. a=0;//false
  27. a=NaN;//false
  28. a=Infinity;//true
  29. //调用Boolean()函数来将a转换为布尔值
  30. a="hello";//true
  31. a="错误";//true
  32. a="";//false
  33. a=null;//false
  34. a=undefined;//false
  35. a=Boolean(a);
  36. console.log(typeof a);
  37. console.log(a);
  38. </script>
  39. </head>
  40. <body>
  41. </body>
  42. </html>