簡體   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