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:
ARR.push(KEY)
and then use ARR[KEY]=VAL
format afterwards?push() The push() method adds one or more elements to the end of an array and returns the new length of the array.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With