admin管理员组

文章数量:1303389

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.

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.

Share Improve this question asked Apr 29, 2012 at 1:55 createbangcreatebang 2,4231 gold badge14 silver badges14 bronze badges 1
  • If you just do console.log(this + "") or console.log(this.toString()), it'll give you the string primitive you're expecting. – user1106925 Commented Apr 29, 2012 at 2:23
Add a ment  | 

2 Answers 2

Reset to default 8

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);
});

The reason is because this is very plicated 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

本文标签: javascriptArray each() loop returning string instead of value in jQueryStack Overflow