美文网首页
js中forEach,for in,for of

js中forEach,for in,for of

作者: baby_honour | 来源:发表于2018-11-05 12:00 被阅读4次

一般的遍历数组的方法

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]);  
}; 

用for in不仅可以对数组,也可以对enumerable对象操作

var A = {a:1,b:2,c:3,d:"hello world"};  
for(let k in A) {  
    console.log(k,A[k]);  
} 

forEach

array.forEach(v=>{  
    console.log(v);  
});
array.forEach(function(v){  
    console.log(v);  
});

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一样,是直接得到值
新出来的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);  
    } 

参考:https://www.cnblogs.com/amujoe/p/8875053.html

相关文章

网友评论

      本文标题:js中forEach,for in,for of

      本文链接:https://www.haomeiwen.com/subject/arxsxqtx.html