Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does running jquery each() on an array containing strings break each string into an array of the individual characters?

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

?

like image 270
Inigo Avatar asked Dec 07 '25 06:12

Inigo


2 Answers

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());
})
like image 64
Sami Avatar answered Dec 09 '25 20:12

Sami


you can try this

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

    console.log(value);
})
like image 31
Rajat Bhadauria Avatar answered Dec 09 '25 19:12

Rajat Bhadauria