3

I have loaded jquery and I have an array (object) containing strings like so:

window.stack = [
  "header",
  "nav",
  ".content",
  "footer"
];

When I run this through a loop using jquery's each() function and try to get each of my strings back again like this:

$.each(window.stack,function(){
    var h = this;
    console.log(h);
})

...I get this:

String [ "h", "e", "a", "d", "e", "r" ]
String [ "n", "a", "v" ]
String [ ".", "c", "o", "n", "t", "e", "n", "t" ]
String [ "f", "o", "o", "t", "e", "r" ]

Why don't I just get:

header
nav
.content
footer

?

Inigo
  • 8,110
  • 18
  • 62
  • 110
  • This question may help: http://stackoverflow.com/questions/2522765/strings-in-array-are-no-longer-strings-after-jquery-each – NiallMitch14 Feb 23 '16 at 11:59

2 Answers2

2

You can use $.each(window.stack, function(key, value).

From http://api.jquery.com/jquery.each/

The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.

So, if you want to use this,

$.each(window.stack,function(){
 var h = this;
 console.log(h.toString());
})
Sami
  • 3,926
  • 1
  • 29
  • 42
  • "Javascript will always wrap the this value as an Object even if it is a simple string or number value" <-- That's the answer right there, I didn't get this. Thanks. – Inigo Feb 23 '16 at 12:04
1

you can try this

  $.each(window.stack,function(key,value){

    console.log(value);
})
Rajat Bhadauria
  • 260
  • 2
  • 12