我正在尝试实现 w2ui
multi select在正在处理的 d3 图表之一中。
这是示例 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)方法类似。
关于javascript - Array.prototype 导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37912320/