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]);
}
二、用for in的方遍历数组
for(let index in array) {
console.log(index,array[index]);
};
三、forEach
array.forEach(v=>{
console.log(v);
});
array.forEach(function(v){
console.log(v);
});
四、用for in不仅可以对数组,也可以对enumerable对象操作
var A = {a:1,b:2,c:3,d:”hello world”};
for(let k in A) {
console.log(k,A[k]);
}
五、在ES6中,增加了一个for of循环,使用起来很简单
for(let v of array) {
console.log(v);
};
let s = “helloabc”;
for(let c of s) {
console.log(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);
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!