您的位置:首页 > 博客中心 > 编程语言 >

JavaScript for/for in/while/do while应用场景

时间:2022-03-29 01:52

一、循环的适用场景(建议)

  •  for : 比较适合遍历数组,字符串等等。
  •  for in : 比较适合遍历对象,遍历对象时使用这个再合适不过。
  •  while : while 与 for 的使用场景差不多。
  •  do while : 至少执行一边的循环,遍历数组和字符串也很方便。

二、while遍历数组需要注意:

如果数组中有 0,null,false,undefined 或者空字符串等在 js 中被认为等价于 false 的值,会提前结束遍历。可以通过改成判断数组长度,来避免该问题。

原代码:

while (cars[i]) {
    document.write(cars[i] + "<br>");
    i++;
}

更改后:

while (i < cars.length) {
    document.write(cars[i] + "<br>");
    i++;
}

本文参考:

https://www.runoob.com/js/js-loop-while.html

本类排行

今日推荐

热门手游