在JavaScript中扩展Array原型 [英] Extending Array prototype in JavaScript

查看:69
本文介绍了在JavaScript中扩展Array原型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己想要对数组中的所有项进行某些操作,我希望JavaScript有类似C#的LINQ。所以,为此,我掀起了Array原型的一些扩展:

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:

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

这使得如果需要对数组进行数学处理,则更容易使用数组。是否有任何建议反对使用这样的模式?我想我应该创建自己继承自Array的原型的类型,但除此之外,如果这些数组中只有数字,这是个好主意吗?

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然后修改THAT是最安全的做事方式,因为它可以保证不会与其他可能尝试做同样事情的开发人员发生冲突(即使他们不应该这样做)。

Generally speaking you should avoid extending base objects because 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).

基本上,尽可能避免扩展基础对象,因为与扩展数组对象相比,它可能会让您陷入麻烦,实际上没什么好处。

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.

这篇关于在JavaScript中扩展Array原型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆