简体   繁体   English

有没有办法扩展JavaScript对象数组?

[英]Is there a way to extend an array of JavaScript objects?

In JavaScript you can extend the functionality of an object with prototype. 在JavaScript中,您可以使用原型扩展对象的功能。

Person.prototype.fullName = function () {
    return this.first + this.last;
};

I run into scenarios a lot where I need to process something on an array of specific objects. 我遇到了很多情况,这些情况下我需要对一系列特定对象进行处理。 These are cases where it would be nice for the functionality to be linked to that object type, as opposed to just passing as an array parameter. 在这些情况下,最好将功能链接到该对象类型,而不是仅将其作为数组参数传递。 I am aware that it is unadvised to extend the JavaScript Array. 我知道不建议扩展JavaScript数组。

Is there an equivalent standard to extend the functionality of an array of objects? 是否有等效的标准来扩展对象数组的功能? Here is a pseudo-example of what I mean: 这是我的意思的一个伪示例:

Person(Array).prototype.groupByAges = function () {
    // logic here that would group by ages
    // { '0-15': [person, person], '16-18': [person, person], etc. }

    return list;
};

// could be used like this
const list = persons.groupByAges();

What I have tried: 我试过的

  1. writing functions like getAgeGroupsByPerson(arr) which end up cluttering code 编写类似getAgeGroupsByPerson(arr)函数,这些函数getAgeGroupsByPerson(arr)代码混乱
  2. JQuery.grep() and JavaScript arr.map() which help but does not link the functionality to that specific object type. JQuery.grep()和JavaScript arr.map()有助于但不将功能链接到该特定对象类型。

Note: I realize that there may be better ways to logically solve the specific age grouping problem that I have described. 注意:我意识到,可能有更好的方法可以从逻辑上解决我所描述的特定年龄分组问题。 It is just an example to demonstrate my point. 这只是说明我的观点的一个例子。 Thank you. 谢谢。

I see two different approaches that would satisfy your requirements 我看到两种可以满足您要求的方法

1) Write a class that extends Array and stick your array in there 1)编写一个扩展Array并将其粘贴在其中的类

class MyArray extends Array {
  groupByAge() {
    console.log(this);
  }
}


let a = MyArray.from([1,2,3]);
a.groupByAge();

2) Write a normal function that takes an array of your objects and does work on it. 2)编写一个正常的函数,该函数接受对象数组并对其进行处理。

function groupByAge(array) {
   console.log(this);
}

There is more work than payoff to try to extend a new Array function IMO than doing both of the above. 尝试完成新的Array函数IMO的工作比付出更多,而不是做上述两项。 If JS classes isn't something you can utilize then I'd suggest going for the function and just call that "everywhere". 如果您不能利用JS类,那么我建议您使用该函数,然后将其命名为“ Everywhere”。

Upside to both approaches is that they are quite easily testable and that's something that we want. 两种方法的好处是它们很容易测试,这是我们想要的。

You can decorate your arrays 您可以装饰arrays

 let decorate = (array) => { array.groupByAges = function() { console.log(`Grouping = ${this}`); } return array; } decorate([1,2,3]).groupByAges(); 

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

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