牛骨文教育服务平台(让学习变的简单)
博文笔记

js笔记一:js中forEach,for in,for of循环的用法

创建时间:2017-01-04 投稿人: 浏览次数:13783
(这些例子已经在node.js 6.9.x下,运行通过)


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是遍历不了的


js笔记十一:js监测变化并动态加载
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。