文章目录
- 普通for循环
- for in 和 for of
- 普通对象为什么不能使用for of
- forEach
- 注意
普通for循环
普通用法:通过初始条件、结束条件和递增条件来循环执行语句块。
for循环最常用的地方是利用索引来遍历数组:
1
2
3
4
5
6
7var arr = ['Apple', 'Google', 'Microsoft']; var i, x; for (i=0; i<arr.length; i++) { x = arr[i]; console.log(x); // 'Apple' 'Google' 'Microsoft' }
for循环的3个条件都是可以省略的,如果没有退出循环的判断条件,就必须使用break语句退出循环,否则就是死循环:
1
2
3
4
5
6
7
8var x = 0; for (;;) { // 将无限循环下去 if (x > 100) { break; // 通过if判断来退出循环 } x ++; }
for in 和 for of
for … in循环遍历的实际上是对象的属性名称(一般都是对对象使用for…in),如果对一个Array数组(实际上也是一个对象,js中一切皆是对象)使用,它的每个元素的索引被视为一个属性。
当我们手动给Array对象添加了额外的属性后,for … in循环将带来意想不到的意外效果:
1
2
3
4
5
6
7var a = ['A', 'B', 'C']; a.name = 'Hello'; for (var x in a) { console.log(x); // '0', '1', '2', 'name' } console.log(a.length);// 3
for … in循环将把name包括在内(for in遍历出来的是字符串,要注意),但Array的length属性却不包括在内。
另外 for in 循环的时候,不仅遍历自身的属性,还会找到 prototype 上去,所以最好在循环体内加一个判断,就用 obj[i].hasOwnProperty(i),这样就避免遍历出太多不需要的属性。
hasOwnProperty一般是过滤掉对象继承的属性!
所以这个就算使用hasOwnProperty也不行(其是直接在实例对象上加上的属性,相当于是实例对象自己有的)
1
2
3
4
5
6
7
8var a = ['A', 'B', 'C']; a.name = 'Hello'; for (var key in a) { if (a.hasOwnProperty(key)) { console.log(key);//0 1 2 name } }
for of 循环是 Es6 中新增的语句,功能非常强大用来替代 for in 和 forEach,for-of循环不仅支持数组,还支持大多数类数组对象,它允许你遍历 Arrays(数组), Strings(字符串), Maps(映射), Sets(集合)等可迭代(Iterable data)的数据结构,注意它的兼容性。
for … of循环则完全修复了这些问题,它只循环集合本身的元素(这里集合本身的元素不太好理解,什么是集合本身的元素?为什么name就不是集合本身元素?不是直接加上去的嘛?):
1
2
3
4
5
6var a = ['A', 'B', 'C']; a.name = 'Hello'; for (var x of a) { console.log(x); // 'A', 'B', 'C' }
菜鸟感觉可能和下面有关,那就是for of不能遍历普通对象,所以即使你加上去了,其也不会去遍历!
for of虽然可以只循环集合本身的元素,却不能循环普通对象
1
2
3
4
5
6
7
8
9let b = { name:"pbw", age:"18", afk:'发客户分级艾克非' } for (var z of b) { console.log(z); };
报错:
由此可以看出,最好对对象使用for in,对数组等使用for of和普通循环!
普通对象为什么不能使用for of
感谢:可以迭代大部分数据类型的 for…of 为什么不能遍历普通对象?
forEach
forEach方法,它接收一个函数,每次迭代就自动回调该函数,有三个参数。以Array为例:
1
2
3
4
5
6
7
8var a = ['A', 'B', 'C']; a.forEach(function (element, index, array) { // element: 指向当前元素的值 // index: 指向当前索引 // array: 指向Array对象本身 console.log(element + ', index = ' + index, array); });
打印结果:
Set与Array类似,但Set没有索引,因此回调函数的前两个参数都是元素本身:
1
2
3
4
5
6
7var s = new Set(['A', 'B', 'C']); s.forEach(function (element, sameElement, set) { console.log(element); console.log(sameElement); console.log(set); });
Map(value-key的结构,具有极快的查找速度) 的回调函数参数依次为value、key和map本身:
1
2
3
4
5var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]); m.forEach(function (value, key, map) { console.log(value,key,map); });
注意
forEach不能使用break或者continue,来提前终止或者跳过步骤,会报错;使用return true或者return false只能代替continue:
1
2
3
4
5
6
7
8
9
10
11
12
13
14var a = ['A', 'B', 'C']; a.forEach(function (element, index, array) { // element: 指向当前元素的值 // index: 指向当前索引 // array: 指向Array对象本身 if(index == 1){ return false; // break; // continue; // return true; } console.log(element + ', index = ' + index,array); });
结果:
最后
以上就是开心铃铛最近收集整理的关于js中的for循环总结普通for循环for in 和 for offorEach的全部内容,更多相关js中的for循环总结普通for循环for内容请搜索靠谱客的其他文章。
发表评论 取消回复