3

我想提交给underscore.js_.difference的数组数量不定。我怎样才能将它们提交给这个函数?

var arrays = [[1,2,3], [3,4,5], [6,3,6]];
var result = _.difference.apply(null, arrays);

似乎工作。但我不确定这是否应该apply()被使用。有没有更好的方法?

4

1 回答 1

1

您的解决方案看起来不错,但我会将上下文更改为下划线对象本身:

var result = _.difference.apply(_, arrays);

它的工作原理是一样的,因为this在 method 中没有使用关键字,但保留上下文是一个好习惯。


例如。当您this在自己的 mixin 中使用时,不保留上下文会破坏它:

_.mixin({
  getVersion: function() {
    return this.VERSION;
  }
});

_.getVersion();               // '1.4.4'
_.getVersion.apply(null, []); // undefined
_.getVersion.apply(_, []);    // '1.4.4'
于 2013-11-07T17:41:17.067 回答