SoFunction
Updated on 2025-03-01

Summary of examples of usage forEach, for in and for of in JS

1. forEach

1.1 Iterate over the array

var array = [1,2,3,4,5,6];
/**
 * currentValue Current element
 * index The index value of the current element
 * arr The array object to which the current element belongs
 **/
(function(currentValue, index, arr) {
    ("index: " + index + "; currentValue: ", currentValue);
});

1.2 Traversing the object

var object = {"a":1, "b":2, "c":3};
/**
 * currentValue Current element
 * index The index value of the current element
 * arr The array object to which the current element belongs
 **/
(object).forEach(function(currentValue, index, arr) {
    ("index: " + index + "; currentValue: ", currentValue);
});

2. for in

2.1 Iterate over the array

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

2.2 Traversing the object

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

III. for of

3.1 traversing the array

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

3.2 Traversing the object

for of cannot directly traverse arrays, and you need to add properties to the object

3.2.1 Method 1

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

3.2.2 Method 2 uses ES6 function*()

var obj = {
    a:1,
    b:2,
    c:3
};
obj[] = function*(){
    var keys = (obj);
    for(var k in keys){
        yield [k, keys[k]]
    }
};
for(var [k, v] of obj){
    (k, v);
}

Interested friends can use the online tools of this site:http://tools./code/HtmlJsRunTest the above code running effect!