forEach、for...in和for..of比较

forEach是遍历数组中的值:

var arr=['one','two','three'];
arr.forEach(function(value){
	console.log(value);
})
//one
//two
//three

这种写法的问题在于,无法中途跳出forEach循环,break命令或return命令都不管用。
for…in是遍历数组的键名

var arr=['one','two','three'];
for(var i in arr){
console.log(i);
}
//0
//1
//2

缺点是:
数组的键名是数字,但是for…in循环是以字符串作为键名,“0”、“1”、"2"等
for…in不仅可以遍历数字键名,还可以遍历手动添加的其他的键,甚至包括原型链上的键

var arr=['one','two','three'];
arr.foo='four';
for(var i in arr){
console.log(i);
}
//0
//1
//2
//foo

某些情况下,for…in会以任意顺序遍历键名
for…in主要是为遍历对象而设计,不适合遍历数组。
for…of可以遍历数据结构中部署了Symbol.iterator属性的成员
for…of可以使用的范围包括数组、Set和Map结构,某些类似数组的对象(比如arguments对象、DOM NodeList对象)、Generator对象,以及字符串。

//数组中的遍历器只返回具有数字索引的属性
var arr=['one','two','three'];
arr.foo='four';
for(var i of arr){
	console.log(i);
}
//one
//two
//three
//Set和Map
var set=new Set(["a","b","a","c"]);
for(var i of set){
console.log(i);
}
//a
//b
//c
var map=new Map();
map.set("age","18");
map.set("name","yf")
for(var [key,value] of map){
	console.log(key+":"+value);
}
//age:18
//name:yf
//字符串
let str="hello";
for(let val of str){
	console.log(val);
}
//h e l l o

for…of可以通过break、continue和return实现跳出循环

猜你喜欢

转载自blog.csdn.net/qq_41805715/article/details/84710713
今日推荐