欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JS 中forEach,for in、for of用法實例總結(jié)

 更新時間:2023年05月24日 09:11:03   作者:書香水墨  
這篇文章主要介紹了JS 中forEach,for in、for of用法,結(jié)合實例形式總結(jié)分析了JS 中forEach,for in、for of的基本功能、使用方法與相關注意事項,需要的朋友可以參考下

一、forEach

1.1 遍歷數(shù)組

var array = [1,2,3,4,5,6];
/**
* currentValue 當前元素
* index 當前元素的索引值
* arr 當前元素所屬的數(shù)組對象
**/
array.forEach(function(currentValue, index, arr) {
?? ?console.log("index: " + index + "; currentValue: ", currentValue);
});

1.2 遍歷對象

var object = {"a":1, "b":2, "c":3};
/**
* currentValue 當前元素
* index 當前元素的索引值
* arr 當前元素所屬的數(shù)組對象
**/
Object.keys(object).forEach(function(currentValue, index, arr) {
?? ?console.log("index: " + index + "; currentValue: ", currentValue);
});

二、for in

2.1 遍歷數(shù)組

var array = [1,2,3,4,5,6];
for (var index in array) {
?? ?console.log("index: " + index + "; currentValue: ", array[index]);
}

2.2 遍歷對象

var object = {"a":1, "b":2, "c":3};
for (var index in object) {
?? ?console.log("index: " + index + "; currentValue: ", object[index]);
}

三、for of

3.1 遍歷數(shù)組

var array = [1,2,3,4,5,6];
for (var varlue of array) {
?? ?console.log("currentValue: ", varlue);
}

3.2 遍歷對象

for of不能直接遍歷數(shù)組,需要為對象增加 Symbol.iterator 屬性

3.2.1 方法一

var obj = {
? ? a:1,
? ? b:2,
? ? c:3
};
obj[Symbol.iterator] = function(){
? ? var keys = Object.keys(this);
? ? var count = 0;
? ? return {
? ? ? ? next(){
? ? ? ? ? ? if(count < keys.length) {
? ? ? ? ? ? ? ? return {value:obj[keys[count++]], done:false};
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? return {value:undefined, done:true};
? ? ? ? ? ? }
? ? ? ? }
? ? }
};
for(var k of obj){
? ? console.log(k);
}

3.2.2 方法二使用ES6 function*()

var obj = {
? ? a:1,
? ? b:2,
? ? c:3
};
obj[Symbol.iterator] = function*(){
? ? var keys = Object.keys(obj);
? ? for(var k in keys){
? ? ? ? yield [k, keys[k]]
? ? }
};
for(var [k, v] of obj){
? ? console.log(k, v);
}

感興趣的朋友可以使用本站在線工具:http://tools.jb51.net/code/HtmlJsRun 測試上述代碼運行效果!

相關文章

最新評論