var obj = [ "one", "two", "three"];
$.each(obj, function() {
console.log(this);
});
The output I get is
{ '0': 'o', '1': 'n', '2': 'e' }
{ '0': 't', '1': 'w', '2': 'o' }
{ '0': 't', '1': 'h', '2': 'r', '3': 'e', '4': 'e' }
I suppose to get "one" "two" "three", but I get the following weird results, anyone can explain?
this is always an object there. A string object consists of key/value pairs where keys are indices and values are characters at that index in the string. Try Object("foo") to create such an object yourself.
By using strict mode you can suppress that:
$.each(obj, function() {
"use strict";
console.log(this);
});
In javascript (not just jQuery), this is a special keyword referring to an object bound to the current scope (unless it has been changed). Within the $.each function, the scope context of the loop function (the function you pass) is bound to the item that you're looping. That may be the case, but it isn't reliable nor is it very useful or interesting.
Observe:
var clams = { 'tomato!':'gross' };
var items = ["one", "two", "three"];
$.each(items, function (index, item) {
console.log('this',this);
console.log('item', item);
}.bind(clams));
Try it: http://jsfiddle.net/LBfet/
While it is possible to use this within an $.each loop, I would suggest using it the way the documentation provides, which is that your looping function support the signature callback(indexInArray, valueOfElement).
Documentation: http://api.jquery.com/jQuery.each/
Consider it a quirk.
More Reading
jQuery.each - http://api.jquery.com/jQuery.each/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