So if the variable "this" is currently set to an object,
{ name: "The old this" }
the following code will change it in the loop
var array = [1, 2, 3];
$.each(array,
function(i, e){
alert(this.name);
}
);
this.name wont be found, instead the variable "this" is set to the same as 'e' during the loop execution
Is it possible to have jquery not clobber the this variable on $.each loops?
each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.
To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.
Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.
If you use the native .forEach
instead of $.each
, you can set the this
value for the callback by sending a second argument...
array.forEach(function(e, i) {
alert(this.name);
}, this);
You'll need to patch older browsers, including IE8...
Or you can use jQuery's $.proxy
to return a function with the desired this
value...
$.each(array, $.proxy(function(i, e) {
alert(this.name);
}, this) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With