向来心是看客心 奈何人是局中人
先写一个数组:
var arr = [1,2,3,4,5]; console.log(arr);
一、forEach():
代码:
var arr = [1,2,3,4,5]; arr.forEach(function(i){ console.log(i) })
输出结果:
二、for..... in():
代码:
var arr = [1,2,3,4,5]; for(var i in arr){ console.log(i) }
输出结果:
输出的竟然是索引下标。
换种方法试下:
代码:
var arr = [1,2,3,4,5]; for(var i in arr){ console.log(arr[i]) }
输出结果:
三、for循环:
代码
var arr = [1,2,3,4,5]; for(var index = 0;index<arr.length;index++){ console.log(arr[index]); }
输出结果:
结论:
forEach 简洁但不可中断。
for in虽然可以用来遍历数组,但是他主要是用来遍历对象的;而且他还会将原型中的方法遍历出来;
for 循环使用于长度已知的操作对象。
逆战班
2020/4/6
原文:https://www.cnblogs.com/miss-vogel/p/12643739.html