JS for和forEach循环运用
for循环
for (i = 0; i < loopTimes; i++) {
console.log(i);
}
for..in循环
for (property in obj) {
console.log(property, obj[property]);
}
for..of循环
for..of循环修复了for..in存在的问题,它只遍历属于对象本身的属性值。
且这个对象必须是iterable可被迭代的。
如Array, Map, Set。
for (element of iterable) {
console.log(element);
}
forEach: 类似for循环,无返回值
var arr = [1,2,3,4,5];
arr.forEach((item,index,array) => {
console.log(index + ‘–‘ + item);;// 0–1 1–2 2–3 … console.log(array); // [1, 2, 3, 4, 5]
})