- 注意return不要出现在循环体中,是一种错误语法,return用于函数体返回值
for
-
for(j = 0,len=arr.length; j < len; j++) { //执行代码 }
forEach
-
遍历数组中的每一项,没有返回值,对原数组没有影响,不支持IE
没有返回值//参数:value数组中的当前项的值, index当前项的下标, array原始数组;
break和continue都不可使用(需要自己用其他方式来控制break和continue)
return的作用是相当于continue
arr.forEach((value,index,array)=>{//箭头函数的写法 //执行代码 }) arr.forEach(function (value,index,array){//传统写法 //执行代码 })
For-In 循环
- 循环遍历对象的属性会更佳(当然也可以遍历数组)
- 在Js中for in 是用来循环遍历对象的属性的,但是这个功能是有局限的
- 所遍历的属性必须是对象自定义的属性,对象的内置属性无法进行遍历
- 顺序不确定
- E6/7/8浏览器不支持
var person={fname:"John",lname:"Doe",age:25}; for (x in person) { txt=txt + person[x]; }
for-of 循环
-
for…of 语句创建一个循环来迭代可迭代的对象。
-
在 ES6 中引入的 for…of 循环,以替代 for…in 和 forEach() ,并支持新的迭代协议。
-
for…of 允许你遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代的数据结构等。
-
for…of 循环仅适用于迭代。 而普通对象不可迭代
-
顺序是固定的,数组以数组顺序遍历
-
数组:
const iterable = ['mini', 'middle', 'mo']; for (const value of iterable) { console.log(value); } //打印的是iterable 数组中的每一个值mini,middle,mo -
Maps
const iterable = new Map([['one', 1], ['two', 2]]); for (const [key, value] of iterable) { console.log(`Key: ${key} and Value: ${value}`); } // Key: one and Value: 1 -
String
const iterable = 'javascript'; for (const value of iterable) { console.log(value); } // "j","a",.....依次

被折叠的 条评论
为什么被折叠?



