3

我正在尝试在正在处理的 d3 图表之一中实现w2ui 多选。

这是解决问题的示例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

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

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

4

1 回答 1

7

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

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

于 2016-06-19T22:38:51.170 回答