7

我在阅读如何在 JavaScript 中获取查询字符串值?在 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;
}

但不是这样:

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

我重写了如下代码:

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

它有效。现在的问题是:

  • 为什么有人会使用数组来进行这种回复?
  • 为什么有人会使用ARR.push(KEY)然后再使用ARR[KEY]=VAL格式?
4

4 回答 4

2

这导致vars既是键数组又是字典。
我能想到的唯一好理由是保持查询参数的顺序,这在字典 中没有定义。

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)

于 2012-04-07T08:52:19.763 回答
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.

于 2012-04-07T08:59:19.787 回答
1

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

于 2012-04-07T08:53:11.630 回答
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.

于 2012-04-07T08:59:37.400 回答