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 + "")
orconsole.log(this.toString())
, it'll give you the string primitive you're expecting. – user1106925 Commented Apr 29, 2012 at 2:23
2 Answers
Reset to default 8the 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
版权声明:本文标题:javascript - Array .each() loop returning string instead of value in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741739616a2395222.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论