js中循环语句有forEach,for in,for of 三种了
一般的遍历数组的方法:
-
var array = [1,2,3,4,5,6,7]; -
for (var i = 0; i < array.length; i) { -
console.log(i,array[i]); -
}
结果如下:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
用for in的方遍历数组
-
for(let index in array) { -
console.log(index,array[index]); -
};
结果如下:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
上述两个结果是一样的.
也可以用forEach
-
array.forEach(v=>{ -
console.log(v); -
});
结果如下:
1
2
3
4
5
6
7
forEach的缺点也是很明显的,就是不能中断
除了上面方法,还可以用forEach
可以使用forEach方法,这个是数组对象自带的:
-
array.forEach(function(v) { -
console.log(v); -
});
结果如下:
1
2
3
4
5
6
7
用for in不仅可以对数组,也可以对enumerable对象操作
如下:代码
-
var A = {a:1,b:2,c:3,d:"hello world"}; -
for(let k in A) { -
console.log(k,A[k]); -
}
结果如下:
a 1
b 2
c 3
d hello world
在ES6中,增加了一个for of循环,使用起来很简单
对于数组
-
for(let v of array) { -
console.log(v); -
};
结果如下:
1
2
3
4
5
6
7
对于字符串则可以
-
let s = "helloabc"; -
for(let c of s) { -
console.log(c); -
}
结果如下:
h
e
l
l
o
a
b
c
-
for(let index in s) { -
console.log(index,s[index]); -
}
结果如下:
0 h
1 e
2 l
3 l
4 o
5 a
6 b
7 c
总结来说:for in总是得到对像的key或数组,字符串的下标,而for of和forEach一样,是直接得到值
结果for of不能对象用
对于新出来的Map,Set上面
如下
-
var set = new Set(); -
set.add("a").add("b").add("d").add("c"); -
var map = new Map(); -
map.set("a",1).set("b",2).set(999,3); -
for (let v of set) { -
console.log(v); -
} -
console.log("--------------------"); -
for(let [k,v] of map) { -
console.log(k,v); -
}
结果如下:
a
b
d
c
--------------------
a 1
b 2
999 3
然这个用for in是遍历不了的
原文章的链接:https://blog.youkuaiyun.com/zdhsoft/article/details/54017183

本文详细介绍了JavaScript中常用的循环语句,包括for、for-in、for-of及forEach等,并通过实例对比了它们的不同应用场景和特点。
243

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



