array.protype引起错误



正在尝试实现 w2ui多选择的D3图表中的一个。

这是与问题的示例JSFIDDLE的链接。

我有三个功能:

//get a column of an array
Array.prototype.getColumn = function(name) {
  return this.map(function(el) {
    // gets corresponding 'column'
    if (el.hasOwnProperty(name)) return el[name];
    // removes undefined values
  }).filter(function(el) {
    return typeof el != 'undefined';
  });
};
//remove duplicates in an array
Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};
Array.prototype.unique = function() {
  var arr = [];
  for (var i = 0; i < this.length; i++) {
    if (!arr.contains(this[i])) {
      arr.push(this[i]);
    }
  }
  return arr;
}

我需要实现这三个功能。

问题是,每当我尝试使用Array.prototype实现这些功能时,我都会在MultiSelect中获得"undefined"中的项目。"undefined"的数量直接与Array.prototype函数的函数数量直接证明。

如果我删除了这些功能,则可以使多选择性正常工作(只有多选部分,而不是整个图表。我不明白,是什么导致了错误。

任何帮助将不胜感激。谢谢。

在与第三方库合作时,与核心JavaScript对象一般混乱是一个坏主意。如果您仍然想以这种方式保留并解决此特定问题,请使用对象。DefineProperty方法,请关闭枚举的位

所以例如更改

Array.prototype.contains = function(v) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === v) return true;
  }
  return false;
};

to

Object.defineProperty(Array.prototype, 'contains', {
    enumerable: false,
    value: function(v) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === v) return true;
        }
        return false;
    }
});

且与您添加的其他原型方法相似。

最新更新