Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 611
createbang Avatar asked Feb 18 '26 01:02

createbang


2 Answers

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);
});
like image 142
Joseph Avatar answered Feb 19 '26 13:02

Joseph


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
like image 33
dkamins Avatar answered Feb 19 '26 13:02

dkamins



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!