我正在尝试在正在开发的d3图表之一中实现w2ui multi select

这是带有问题的示例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实现这些功能时,我都将多选项作为"undefined"获得。 "undefined"的数量与Array.prototype函数的功能数量成正比。

如果删除了这些功能,我可以使多选功能正常工作(只有多选部件,而不是整个图表。我不明白,这是导致错误的原因。

任何帮助表示赞赏。谢谢。

最佳答案

通常,在使用第三方库时,弄乱核心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;
    }
});

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

09-10 04:22
查看更多