Array.prototype 导致错误

Array.prototype causing error

我正在尝试在其中一个正在处理的 d3 图表中实施 w2ui multi select

这是 link 样本 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个函数的函数数量成正比。

如果我删除这些功能,我可以让 multi-select 正常工作(只有 multi-select 部分,而不是整个图表。我不明白,是什么导致了错误。

感谢任何帮助。谢谢。

一般来说,当您使用第三方库时,弄乱核心 javascript 对象是个坏主意。如果您仍然想保持这种方式并解决这个特定问题,请使用 Object.defineProperty 方法,关闭可枚举位

所以例如更改

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

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;
    }
});

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