找回密码
 立即注册
首页 业界区 业界 JavaScript —— 判断语句与循环语句

JavaScript —— 判断语句与循环语句

悯拄等 2025-6-6 19:13:57
判断语句

JavaScript中的if-else语句与C++、Python、Java中类似。



  • 直接输出到控制台:
test.html中的内容为:
  1. [/code]
  2. [list]
  3. [*][size=4]使用输入输出来写:[/size]
  4. [/list]test.js中的内容为:
  5. [code]let input = document.querySelector(".input");
  6. let run = document.querySelector("button");
  7. let output = document.querySelector("pre");
  8. function main() {
  9.     // 给<run>元素添加监听事件。当触发“click”时,执行function()函数
  10.     run.addEventListener("click", function(){
  11.         let score = parseInt(input.value);  // 获取textarea中的input的值(输入)
  12.         let res;
  13.         if (score >= 85) {
  14.             res = "A";
  15.         } else if (score >= 70) {
  16.             res = "B";
  17.         } else if (score >= 60) {
  18.             res = "C";
  19.         } else {
  20.             res = "D";
  21.         }
  22.       
  23.         output.innerHTML = res;  // 展示pre内的标签内容(输出)
  24.     })
  25. }
  26. export {
  27.     main
  28. }
复制代码
test.html中的内容为:
  1. <body>
  2.     输入:
  3.     <br>
  4.     <textarea  name="" id="" cols="30" rows="10"></textarea>
  5.     <br>
  6.     <button>Run</button>
  7.     <br>
  8.     <pre></pre>
  9.    
  10. </body>
复制代码
JavaScript中的逻辑运算符也与C++、Java中类似:

  1. |  &&  | 表示 |  与  |
  2. | ---- | ----| ---- |
  3. |  ||  | 表示 |  或  |
  4. | ---- | ----| ---- |
  5. |  !   | 表示 |  非  |
复制代码
循环语句

JavaScript中的循环语句与C++中类似,也包含for、while、do while循环。


for循环:

  1. [/code][size=4]枚举对象或数组时可以使用:[/size]
  2. [list]
  3. [*]for-in循环,可以枚举数组中的下标,以及对象中的key
  4.  
  5. [*]for-of循环,可以枚举数组中的值,以及对象中的value
  6. [/list]
  7. [indent][size=5]while循环:[/size]
  8. [/indent][code]
复制代码
do while循环:

do while语句与while语句非常相似。唯一的区别是,do while语句限制性循环体后检查条件。不管条件的值如何,我们都要至少执行一次循环(无条件执行一次)。

[code][/code]
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册