js中forEach,for in ,for of 循环的用法

js 中循环语句有forEach,for in ,for of ,还有一般的数组的遍历的方法:

let commArray = [1,2,3,4,5,6,7,8,9];
for (let i =0;i<commArray.length; i++) {
console.log(i, commArray[i])
} 
 // 0 1 2 3 4 5 6 7 8 
// 1 2 3 4 5 6 7 8 9

用for in 的方法遍历数组

for (let index in commArray) {
console.log(index, commArray[index])
}
// 0 1 2 3 4 5 6 7 8 
// 1 2 3 4 5 6 7 8 9

用forEach遍历

commArray.forEach((item,index) => {
console.log(item, index)
})
//  1 2 3 4 5 6 7 8 9
// // 0 1 2 3 4 5 6 7 8 

forEach()方法用于调用数组的每个元素,并将元素传递给回调函数,forEach()是Array下的一个方法。
注意:无法使用break 等语句跳出遍历,直到所有的元素都传递给调用的函数,但是可以抛出异常,提前终止循环。

在es6中,新增一个for of 循环,用法如下

for (let v of commArray) {
console.log(v])
} // 1 2 3 4 5 6 7 8 9

对于字符串:

let s = 'helloword'
for (let c of s) {
console.log(c)
} // h e l l o w o r d
for (let index in s) {
console.log(index, s[index])
}
// 0 1 2 3 4 5 6 7 8
// h e l l o w o r d

总结

  • for…in:

    • 循环的是对象的属性;
    • 所以便利数组得到的是索引而不是值;所以要遍历数组,可以采用下标循环。
    • for…in对Array的循环得到的是String而不是Number
  • for…of循环:

    • for of和forEach一样,是直接得到值结果。

    对于新出来的Map,Set属性,for of 可以遍历,但是for in确不能使用

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);
console.log(set, map)
// {"a", "b", "d", "c"}
// {"a" => 1, "b" => 2, 999 => 3}
for (let v of set) {
 console.log(v)
} //  a b c d
for (let [k,v] of map) {
console.log(k,v)
}
// a b 999
// 1 2 3
for (let h in set) {
 console.log(h)
} // undefined
for (let d in map) {
console.log(d)
} // undefined

猜你喜欢

转载自blog.csdn.net/weixin_36430673/article/details/103275137
今日推荐