7

I was reading How can I get query string values in JavaScript? on Stackoverflow and this piece of code from the first reply made me wonder why ´vars.push()´ is used like this?

function getUrlVars()
{
    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.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

But instead of this:

var vars=[];
...
vars.push(hash[0]);
vars[hash[0]] = hash[1];

I rewrote the code like:

var vars={};
...
vars[hash[0]] = hash[1];

and it works. Now the questions are:

  • why would someone use an array for that kind of reply?
  • and why would someone use ARR.push(KEY) and then use ARR[KEY]=VAL format afterwards?
Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104

4 Answers4

2

This results in vars being both an array of keys and a dictionary.
The only good reason I can think of is to keep the order of the query parameters, which is not defined in a dictionary.

Either way, I would note this function removes duplicated query parameters - it only keeps the last value (though the key would be inserted multiple times to the array)

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292
2

The function uses the array both as an array and as an object.

As an array it contains the keys from the query string. As an object it contains properties named from the keys in the query string, and the properties have the values from the query string.

So,m if the query string for example looks like this: a=1&b=2, the array contains the two items "a" and "b", and it has the two properties a with the value 1 and b with the value 2.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

Push will push the key as the last key. So it allows you to have a logical order in the array.

luke14free
  • 2,529
  • 1
  • 17
  • 25
1

push() appends its arguments, in order, to the end of array. It modifies array directly, rather than creating a new array. push(), and its companion method pop(), use arrays to provide the functionality of a first in, last out stack.

Ram
  • 143,282
  • 16
  • 168
  • 197
  • 2
    any langages that has pointers can do OOP. so there is no OOP langage ,since OOP is a programming technique , not a langage paradigme. there are no "objects" in C but you can do OOP in C. javascript is a procedural langage. Scheme or LISP are not for instance. – mpm Apr 07 '12 at 09:10