python foreach用法_js中forEach,for in,for of循环的用法

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

上述两个结果是一样的.

也可以用forEacharray.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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值