Snake Eyes
Snake Eyes

Reputation: 16764

Unable to return length of array created in javascript

I created an array which contains query string values from url

var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

for (var i = 0; i < hashes.length; i++) {
     hash = hashes[i].split('=');
     vars[hash[0]] = hash[1];
}

If I want to iterate it, won't happens anything:

$.each(query_array, function(k, v) {
   console.log(v);
}); 

Then I wrote

console.log(query_array.length);

But my array looks like in Chrome console:

[keyword: "mercedes", redirectTo: "test.aspx", remove: function]

The length returns 0. Why ?

How could I iterate through this kind of array ?

Upvotes: 0

Views: 117

Answers (4)

mohkhan
mohkhan

Reputation: 12305

Ok, I'll give a detailed explanation for this.

Every object in JavaScript can act like a Map(Dictionary). Something like this.

var a = new Object();
a["foo"] = 10;
a["bar"] = 20;

...

Even an Array ([]) is an object. So it will respect the same behavior. Like this...

var arr = [];
arr["foo"] = 10;
arr["bar"] = 20;

But this does not mean you are using the Array as it is supposed to be used. Even though you have added properties to your Array, you have NOT added any element to the array and because of that the length count is 0. So maybe you should keep the count as a separate key/value pair.

Hope you understood.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

vars is not an array. In javascript arrays must always have integer indexes. In your case you using strings as indexes:

vars[hash[0]] = hash[1];

So don't create an array, just create an object:

var vars = {}, hash;

and you will be able to iterate over the properties of this object:

$.each(vars, function(k, v) {
    console.log(k + ': ' + v);
});

Upvotes: 1

Artyom Neustroev
Artyom Neustroev

Reputation: 8715

If you make vars an object, not an array it will work fine for you:

var vars = {}, hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

for (var i = 0; i < hashes.length; i++) {
     hash = hashes[i].split('=');
     vars[hash[0]] = hash[1];
}

console.log(vars) //Object {keyword: "mercedes", redirectTo: "test.aspx", remove: function}

You cannot access an array's element by an index, that is not a number. In your case - the index is not a number.

Upvotes: 3

M.G.Manikandan
M.G.Manikandan

Reputation: 993

var vars = [] should be changed to var vars = {} as your creating Object. [] represents Array.

Then, $.each will work.

Also you can get query string using location.search instead of location.href. Please check the updated code below

var vars = {}, hash;
var hashes = window.location.search.substring(1).split('&');

for (var i = 0; i < hashes.length; i++) {
     hash = hashes[i].split('=');
     vars[hash[0]] = hash[1];
}

Upvotes: 2

Related Questions