Update: I know there are existing implementations of forEach method. The purpose of doing this is to learn and improve my Javascript skills.
I am trying to implement a forEach method for array objects. What I am doing is the following:
var list = ['one', 'two', 'three'];
function forEach(callback){
for(var n = 0; n < this.length; n++){
callback.call(this[n], n);
}
};
list.forEach(function(index){
console.log(index);
console.log(this);
}
);
I am not very good with javascript and I am trying to get better so I’ve been reading a little bit and I now know that if I do this kind of thing, the context of the “forEach” function would be the object which is calling it, in this case “list”.
When this code runs I get the error: “Uncaught TypeError: Object one,two,three has no method ‘forEach'”.
What is it I am not understanding?
Thanks!
I think what you want to do is probably not to attach the foreach function to only the one array you have here, but to make it work for all arrays. To do that, you must edit the Array prototype (something that some people have very strong opinions about, because you can not protect against potential future namespace collisions – but other people find extremely useful). Once the
Array.prototypeobject has a function added to it, you can call that function on any array. Like this:*N.B. to avoid conflict with existing forEach functions (https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach) I have named the function
myForEachwhich I expect to be safe from conflict.