繁体   English   中英

Array.prototype导致错误

[英]Array.prototype causing error

我正在尝试在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函数的functons数量直接相关。

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

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

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

和你添加的其他原型方法类似。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM