Hi and thanks for looking!
I am building my first application in Node.JS and am replacing jQuery-based habits with native JavaScript.
For most items, this is trivial; however, I am finding that I really miss the elegance of jQuery's $.each()
abstraction and I would like to do something similar without relying on jQuery.
Unfortunately, the same code in JavaScript is a bit cumbersome:
myArray = ["item 1", "item 2", "item 3"];
for(i=0; i<myArray.length; i++) {
myArray[i] = "Do Something Here".
};
What I would like to do is have something like this:
myArray = ["item 1", "item 2", "item 3"];
myArray.each(function(){
//do stuff
});
Is there already an extension method out there for accomplishing this? I can't help but think I am re-inventing the wheel. If there isn't anything out there, would an extension method be best?
You have forEach() in EcmaScript 5 : https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
But it's not comptatible with IE < 8.
So you may need to use this lib to be supported by all browsers : https://github.com/kriskowal/es5-shim
ECMA Script 5 incorporates a method of Array called forEach
. Usage is the same as jQuery.each
for Arrays.
There is no need to use a for...in
loop anymore, as Array.forEach
is easily implemented (see the MDN Documentation link, middle of the document).
To clarify, forEach
will loop through arrays only, not objects nor jQuery objects.
You could use
for( i in myArray ){
alert( i + ': ' + myArray[i] ); /* your actions here */
}
jQuery is also available for node incase you'd want to stick to your habit.
npm install jquery
You might want to look into the async library if your objective is to use the foreach in node.js. This allows you to parallelize your foreaches.