user8615957
user8615957

Reputation: 59

Javascript prototyping forEach on Object

I want to create a prototype of forEach on objects and here is my code

Object.prototype.forEach = function(el,index){
    for(var k in Object){
        el = Object[k];
        index = k;
    }
}

Then i created an object to test this

var obj = {x:0,y:0,z:1290}
obj.forEach( function(el, index) {
    console.log(el+" "+index);
    alert();
});

This code returns no errors,but neither does it alert or log into console anything. I checked obj object and it does have forEach in it's _proto_ property.I also tried

Object.prototype.forEach = function(el,index){
    for(var k in this){
        el = this[k];
        index = k;
    }
}

Upvotes: 0

Views: 142

Answers (2)

Viraj Parab
Viraj Parab

Reputation: 91

So Your forEach function of the object is wrong, your forEach function should take a function, you can refer to the forEach of the arrays.

Object.prototype.forEach = function(operation){
    for(var k in this){
        operation(this[k],k,this)
    }
}

var obj = {x:0,y:0,z:1290}

obj.forEach(function(el, index) {
     console.log(el+" "+index);
});

Upvotes: 0

Allen Luce
Allen Luce

Reputation: 8389

You actually want your function to take a function and then call that function with each element and index:

Object.prototype.forEach = function(f) {
    for (var k in this) {
        el = this[k];
        index = k;
        f(el, index);
    }
}

Upvotes: 1

Related Questions