简体   繁体   English

为什么用 array.push() 来做一个 object?

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

I was reading How can I get query string values in JavaScript?我正在阅读如何在 JavaScript 中获取查询字符串值? on Stackoverflow and this piece of code from the first reply made me wonder why ´vars.push()´ is used like this?在 Stackoverflow 上,第一个回复中的这段代码让我想知道为什么要这样使用“vars.push()”?

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?为什么有人会使用ARR.push(KEY)然后再使用ARR[KEY]=VAL格式?

This results in vars being both an array of keys and a dictionary.这导致vars既是键数组又是字典。
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)无论哪种方式,我都会注意到这个 function 删除了重复的查询参数 - 它只保留最后一个值(尽管键会多次插入到数组中)

The function uses the array both as an array and as an object. function 将数组用作数组和 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.作为 object,它包含根据查询字符串中的键命名的属性,并且这些属性具有来自查询字符串的值。

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 .因此,如果查询字符串例如如下所示: a=1&b=2 ,则该数组包含两项“a”和“b”,并且它具有两个属性a的值为1b的值为2 .

Push will push the key as the last key. Push 会将键作为最后一个键进行推送。 So it allows you to have a logical order in the array.所以它允许你在数组中有一个逻辑顺序。

push() appends its arguments, in order, to the end of array. push() 按顺序将其 arguments 附加到数组的末尾。 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. push() 及其配套方法 pop() 使用 arrays 提供先进后出堆栈的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM