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

1 篇文章 0 订阅

js中循环语句有forEach,for in,for of 三种了


一般的遍历数组的方法:

 
  1. var array = [1,2,3,4,5,6,7];

  2. for (var i = 0; i < array.length; i) {

  3. console.log(i,array[i]);

  4. }



结果如下:
0 1
1 2
2 3
3 4
4 5
5 6
6 7


用for in的方遍历数组

 
  1. for(let index in array) {

  2. console.log(index,array[index]);

  3. };



结果如下:
0 1
1 2
2 3
3 4
4 5
5 6
6 7
上述两个结果是一样的.
也可以用forEach

 
  1. array.forEach(v=>{

  2. console.log(v);

  3. });



结果如下:
1
2
3
4
5
6
7
forEach的缺点也是很明显的,就是不能中断


除了上面方法,还可以用forEach
可以使用forEach方法,这个是数组对象自带的:

 
  1. array.forEach(function(v) {

  2. console.log(v);

  3. });



结果如下:
1
2
3
4
5
6
7
用for in不仅可以对数组,也可以对enumerable对象操作
如下:代码

 
  1. var A = {a:1,b:2,c:3,d:"hello world"};

  2. for(let k in A) {

  3. console.log(k,A[k]);

  4. }



结果如下:
a 1
b 2
c 3
d hello world


在ES6中,增加了一个for of循环,使用起来很简单
 对于数组

 
  1. for(let v of array) {

  2. console.log(v);

  3. };



结果如下:
1
2
3
4
5
6
7
对于字符串则可以

 
  1. let s = "helloabc";

  2. for(let c of s) {

  3. console.log(c);

  4. }



结果如下:
h
e
l
l
o
a
b
c

 
  1. for(let index in s) {

  2. console.log(index,s[index]);

  3. }



结果如下:
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上面
如下

 
  1. var set = new Set();

  2. set.add("a").add("b").add("d").add("c");

  3. var map = new Map();

  4. map.set("a",1).set("b",2).set(999,3);

  5. for (let v of set) {

  6. console.log(v);

  7. }

  8. console.log("--------------------");

  9. for(let [k,v] of map) {

  10. console.log(k,v);

  11. }



结果如下:
a
b
d
c
--------------------
a 1
b 2
999 3

然这个用for in是遍历不了的

原文章的链接:https://blog.csdn.net/zdhsoft/article/details/54017183

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值