03.逻辑运算符_非布尔值的与或运算.html 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. && || 非布尔值的情况
  11. -对非布尔值进行与或运算时,
  12. 会先将其转换为布尔值,然后再运算,并且返回原值
  13. -与运算
  14. -如果第一个值为true,则必然返回第二个值
  15. -如果第一个值为false,则直接返回第一个值
  16. -或运算
  17. -如果第一个值为true,则直接返回第一个值
  18. -如果第一个值为false,则返回第二个值
  19. */
  20. var result = 1 && 2;//相当于true && true
  21. //与运算:如果两个值都为true,则返回后边的
  22. console.log(result);//输出结果为2
  23. //与运算:如果两个值中有false,则返回靠前的false
  24. // false && true、true && false结构
  25. result = 0 && 2;//输出结果为0
  26. result = 2 && 0;////输出结果为0
  27. //false && false结构
  28. result = NaN && 0;//输出结果为NaN
  29. result = 0 && NaN;//输出结果为0
  30. // console.log(result);//输出结果为0
  31. //true || true
  32. //如果第一个值为true,则直接返回第一个值
  33. result = 1||2;//结果为1
  34. //如果第一个值为false,则直接返回第二个值
  35. result = NaN || 1;//输出结果为1
  36. result = NaN || 0;//输出结果为0
  37. result = "" || "hello";//输出结果为hello
  38. result = -1 || "你好";//输出结果为-1
  39. console.log(result);
  40. </script>
  41. </head>
  42. <body>
  43. </body>
  44. </html>