0

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;
    }
}
4
  • 1
    It's a reeeeeeeeeeeeeally bad idea to change the prototype of built-in objects. Commented Nov 19, 2017 at 6:21
  • @zerkms why is it? Commented Nov 19, 2017 at 6:21
  • stackoverflow.com/q/14034180/251311 Commented Nov 19, 2017 at 6:22
  • If you want to iterate over the object properties - use Object.entries() or Object.values(). Commented Nov 19, 2017 at 6:23

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.