Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array.push() is used to make an object?

Tags:

javascript

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?
like image 767
AlexStack Avatar asked Apr 07 '12 08:04

AlexStack


People also ask

What does array push () do?

push() The push() method adds one or more elements to the end of an array and returns the new length of the array.

How do you push an array into an object?

In order to push an array into the object in JavaScript, we need to utilize the push() function. With the help of Array push function this task is so much easy to achieve. push() function: The array push() function adds one or more values to the end of the array and returns the new length.

Does array push copy of object?

It depends upon what you're pushing. Objects and arrays are pushed as a pointer to the original object . Built-in primitive types like numbers or booleans are pushed as a copy. So, since objects are not copied in any way, there's no deep or shallow copy for them.

Can you push an array into an array?

Adding Array into the Array using push() push() method. The push() function allows us to push an array into an array. We can add an array into an array, just like adding an element into the Array.


1 Answers

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)

like image 191
Kobi Avatar answered Oct 13 '22 00:10

Kobi