createbang
createbang

Reputation: 2423

Array .each() loop returning string instead of value in jQuery

Sorry, this may be an easy one, but it has me stumped. I'm trying to loop over this array and log out each value, but the script is logging out a string object.

propertiesToSanitize = ["title", "description", "place_name"]
$.each propertiesToSanitize, ->
  console.log this

which converts to jQuery as

var propertiesToSanitize;
propertiesToSanitize = ["title", "description", "place_name"];
$.each(propertiesToSanitize, function() {
  return console.log(this);
});

is returning:

String
  0: "t"
  1: "i"
  2: "t"
  3: "l"
  4: "e"
  length: 5

Any idea why it's returning this instead of just "title" or any other value? Thanks in advance for any help.

Upvotes: 3

Views: 4141

Answers (2)

dkamins
dkamins

Reputation: 21948

The reason is because this is very complicated in JavaScript. The this variable in a callback often references something deep inside the scope stack that you shouldn't rely on. With jQuery's each, "Javascript will always wrap the this value as an Object even if it is a simple string or number value", which is what you're seeing.

jQuery's each passes the value as second argument to your callback. In your JavaScript, you would probably want this:

$.each(propertiesToSanitize, function(idx, val) {
  return console.log(idx + ":" + val);
});

But note also CoffeeScript is very capable of looping over an array without jQuery's help:

for propName in propertiesToSanitize
  console.log propName

Upvotes: 2

Joseph
Joseph

Reputation: 119887

the index and the value for each iteration are provided as a parameter in the callback.

$.each(propertiesToSanitize, function(index,value) {
    console.log(index + ':' + value);
});

Upvotes: 8

Related Questions