在 JavaScript 中扩展数组原型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21945675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending Array prototype in JavaScript
提问by wootscootinboogie
I often found myself wanting to do certain operations for all the items in an array and I wished that JavaScript had something like C#'s LINQ. So, to that end, I whipped up some extensions of the Array prototype:
我经常发现自己想要对数组中的所有项目执行某些操作,并且我希望 JavaScript 具有类似于 C# 的 LINQ 的功能。因此,为此,我对 Array 原型进行了一些扩展:
var data = [1, 2, 3];
Array.prototype.sum = function () {
var total = 0;
for (var i = 0; i < this.length; i++) {
total += this[i];
}
return total;
};
Array.prototype.first = function () {
return this[0];
};
Array.prototype.last = function () {
return this[this.length - 1];
};
Array.prototype.average = function () {
return this.sum() / this.length;
};
Array.prototype.range = function () {
var self = this.sort();
return {
min: self[0],
max: self[this.length-1]
}
};
console.log(data.sum()) <-- 6
This makes working with arrays much easier if you need to do some mathematical processing on them. Are there any words of advice against using a pattern like this? I suppose I should probably make my own type that inherits from Array's prototype, but other than that, if these arrays will only have numbers in them is this an OK idea?
如果您需要对数组进行一些数学处理,这将使使用数组变得更加容易。是否有任何建议反对使用这样的模式?我想我可能应该创建自己的类型来继承自 Array 的原型,但除此之外,如果这些数组中只有数字,这是一个好主意吗?
采纳答案by moberemk
Generally speaking you should avoid extending base objectsbecause it may clash with other extensions of that object. Ideally extending Array and then modifying THAT is the safest way to do things as it is guaranteed to not clash with other developers who might try to do the same thing (even though they shouldn't).
一般来说,您应该避免扩展基础对象,因为它可能与该对象的其他扩展发生冲突。理想情况下,扩展 Array 然后修改 THAT 是最安全的做事方式,因为它保证不会与可能尝试做同样事情的其他开发人员发生冲突(即使他们不应该这样做)。
Basically, avoid extending base objects when possible because it can get you into trouble for very little real benefit compared to extending the array object.
基本上,尽可能避免扩展基础对象,因为与扩展数组对象相比,它可能会给您带来很少的实际好处。