简体   繁体   English

Underscore.js:_.object函数的意外行为

[英]Underscore.js: unexpected behavior with _.object function

Here is the description from the docs of the _.object function. 以下是_.object函数的文档中的描述。

Converts arrays into objects. 将数组转换为对象。 Pass either a single list of [key, value] pairs, or a list of keys, and a list of values. 传递单个[键,值]对列表或键列表以及值列表。 If duplicate keys exist, the last value wins. 如果存在重复键,则最后一个值获胜。

With this example, it works as expected. 通过此示例,它按预期工作。 The key of "1" is assigned the value of "TEST1". “1”的键被赋值为“TEST1”。

_.object(["1", "1"], ["TEST", "TEST1"])

>> Object {1: "TEST1"}


_.object(["1", "1"], ["TEST"])

>> Object {1: undefined}

On this last example, I'd expect the value to be "TEST", but it is undefined. 在最后一个例子中,我希望该值为“TEST”,但它未定义。

Is there a specific reason for this behavior? 这种行为有特定的原因吗?

Thanks. 谢谢。

The behavior is correct. 行为是正确的。 The first call 第一个电话

_.object(["1", "1"], ["TEST", "TEST1"])

associates key 1 with TEST and key 1 with TEST1 (overriding the previous association). 将密钥1与TEST相关联,将密钥1与TEST1相关联(覆盖先前的关联)。

The second call: 第二个电话:

_.object(["1", "1"], ["TEST"])

has the same logic, but the second key 1 is associated with the element in the second position in the 'values' array, which is undefined. 具有相同的逻辑,但第二个键1与'values'数组中第二个位置的元素相关联,这是未定义的。

PS: The code for _.object is this: PS:_. _.object代码是这样的:

  // Converts lists into objects. Pass either a single array of `[key, value]`
  // pairs, or two parallel arrays of the same length -- one of keys, and one of
  // the corresponding values.
  _.object = function(list, values) {
    if (list == null) return {};
    var result = {};
    for (var i = 0, length = list.length; i < length; i++) {
      if (values) {
        result[list[i]] = values[i];
      } else {
        result[list[i][0]] = list[i][1];
      }
    }
    return result;
  };

It seems they do specify that the arrays need to have the same length. 似乎他们确实指定数组需要具有相同的长度。 From the code it is obvious that if the second array is larger, the last values will be ignored and if it is smaller, the last values will be undefined. 从代码中可以明显看出,如果第二个数组较大,则忽略最后一个值,如果它较小,则最后一个值将是未定义的。

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

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