简体   繁体   中英

Please help me debug this error about for/in in Javascript

I am learning about javascript basic, and i have a problem with for/in and for/of.

var courses = [1, 2, 3, 4];

Array.prototype.reduce2 = function (callback, initialValue) {
    var sum = initialValue;
    for(var value of this) {
        sum = callback(sum, value);
    }
    return sum;
}

function func(total, number) {
    return total + number;
}

var sum = courses.reduce2(func, 0);
console.log(sum);

This program is used to define reduce2 function which caculate sum of values in array. In reduce2, I use for/of and it returns the correct result.

for(var value of this) {
    sum = callback(sum, value);
}

However, when i use for/in, it return the incorrect result.

for(var i in this) {
    sum = callback(sum, this[i]);
}

And this is result.

 10function (callback, initialValue) {
    var sum = initialValue;
    for(var i in this) {
        sum = callback(sum, this[i]);
    }
    return sum;
  }

Please help me, thank you very much!!!

From the for...in docs

The for...in statement iterates over all enumerable properties of an object

So, in your case when using for...in at the end of array values i will be reduce2 so this[i] refers to reduce2 function. You can see the output of the below snippet while using for...in .

 var courses = [1, 2, 3, 4]; Array.prototype.reduce2 = function(callback, initialValue) { var sum = initialValue; for (var i in this) { console.log(`this[${i}]: ${this[i]}`); sum = callback(sum, this[i]); } return sum; } function func(total, number) { return total + number; } var sum = courses.reduce2(func, 0);

As, this[i] is being passed to the callback function it's getting appended to the final output ie, function declaration itself is getting appended to 10 in this case.

In order to avoid that while using for...in , we can make use of hasOwnProperty and get the desired output.

 var courses = [1, 2, 3, 4]; Array.prototype.reduce2 = function (callback, initialValue) { var sum = initialValue; for(var i in this) { if(this.hasOwnProperty(i)){ sum = callback(sum, this[i]); } } return sum; } function func(total, number) { return total + number; } var sum = courses.reduce2(func, 0); console.log(sum);

for..in not go thru the indexes. As @nithish mentioned, it will iterate over properties. Better to use classic for loop to iterate the index and get the desired behaviour for the array items.

 var courses = [1, 2, 3, 4]; Array.prototype.reduce2 = function (callback, initialValue) { var sum = initialValue; for (var i = 0; i < this.length; i++) { sum = callback(sum, this[i]); } return sum; }; function func(total, number) { return total + number; } var sum = courses.reduce2(func, 0); console.log(sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM