Enumerating through a JS array in jQuery

OK jQuery experts: So, I'm starting from the Prototype background.

I am doing the following code all the time (or some similar change):

MyObject.prototype.someFunction = function() { var myArray = ["a","b","c"]; myArray.each(function(arrayEntry) { this.printPart(arrayEntry); }, this); } MyObject.prototype.printPart = function(part) { console.log(part); } 

I am viewing jQuery docs - I don't see how to do this.

Is it possible?

In particular, I'm interested in:

  • Iterate through javascript arrays (objects will be nice too).
  • Volume maintenance. Pay attention to the final parameter "this" for each function.
+4
source share
2 answers

You are looking for $.each(array, function(i, element) { ... })

This also handles objects, in which case you get (key, value) in the arguments.

edit - unfortunately, nothing like Prototype inject , and I really miss it. But there is a map in jQuery and this kind of collect in Prototype.

change again - As @Nick notes in his comment, Prototype and jQuery disagree on how to handle the processing of "this". Typically, jQuery calls the handler function with "this", pointing to the obvious corresponding object. The prototype is as free of hands as possible.

+5
source

You don't have to do everything in jQuery. Just add the forEach method if it does not already exist and use it instead. It was so good that ECMAScript 5th ed. accepted it as a standard (inspired by the prototype of each method), but not all browsers have it yet :). Here a specification is implemented that you can use until all browsers have one ( taken from MDC ):

Change Recent versions of Chrome, Safari, Firefox, and Opera already support this. No access to IE, sorry.

 if (!Array.prototype.forEach) { Array.prototype.forEach = function(fun /*, thisp*/) { var len = this.length >>> 0; if (typeof fun != "function") throw new TypeError(); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in this) fun.call(thisp, this[i], i, this); } }; } 

Then use your code as is (change each to forEach ):

 var myArray = ["a","b","c"]; myArray.forEach(function(arrayEntry) { this.printPart(arrayEntry); }, this); 
+1
source

Source: https://habr.com/ru/post/1313925/


All Articles