javascript - 对象数组:建议通过对象键或数组索引或数组项本身选择特定项目?
问题描述
我正在处理一个[]
类对象数组。要求是使用该对象数组来记住当前选定的对象。例如,我有一个名为 的类Person
,它contacts
是var obj = new Person(); contacts.push(obj);
class Person(){
// props, constructors and methods
}
const contacts = [new Person(0), new Person(1), new Person(2), new Person(3)]
var selectedPerson;
所以我希望用户person
从contact
列表中选择任何,所以我正在使用<select>
并且<option>
用户允许选择任何Person
这意味着我正在使用name
道具,所以当用户选择或做任何事情时,我现在从用户选择中Person
获取需要与's 的对象交互或使用它为用户进行少量计算并显示结果。name
Person
Person
我可以onChange
在<select>
onChange(e){
// store the value and filter it out to get the Person object when need calculation
selectedPerson = e.target.value
// store the contact item which is person object and use them everywhere
selectedPerson = contacts.find((person)=> person.name===e.targe.value)
}
// multiple use of the selectedPerson
哪种方法更好,为什么?
有没有其他方法可以更有效地实现同样的目标?
请分享关于该问题未正确提出的想法。
解决方案
你所做的很好,只要在对象name
数组中是独一无二的,Person
并且数组不是真正的大(如果它被输入option
元素就不会)。如果数组内容发生变化,使用name
而不是数组索引也更健壮。
您可以考虑使用 aMap
而不是数组:
const contacts = new Map();
function addContact(person) {
// If you want proactive notification of *replacing* a person, uncomment:
// if (contacts.has(person.name)) {
// throw new Error(`contacts map already contains a person named ${person.name}`);
// }
contacts.set(person.name, person);
}
addContact(new Person(0));
addContact(new Person(1));
// ...
然后在onChange
:
onChange(e) {
const person = contacts.get(e.target.value);
// ...
}
这只是比数组扫描更有效的检索(但这与您将在元素中呈现的人数无关option
),并且对我来说,语义上更适合操作 - 没有机会的重复名称。如果您需要遍历映射中的条目(按添加顺序),映射是可迭代的:
for (const person of contacts.values()) {
// ...
}
推荐阅读
- angular - 如何在 http 标头中为令牌设置变量
- bash - bash 移动失败
- wordpress - 如何将 API 集成到我的 WordPress 项目中?
- angular - Angular 6 - 找不到模块:错误:无法解析“http”
- extjs - extjs 3.4 - 嵌套网格中的扩展器从父行而不是自己的行获取记录
- android - 子主题没有拾取父 textColor
- python - 将列中的值替换为具有相同列名和长度的另一个数据框中的值
- groovy - NiFi 1.5:在 groovy 中使用 ScriptedRecordSetWriter 编写自定义 XML
- optimization - Gurobi 求解器和收敛
- c# - 最小起订量测试方法 C#ASP.NET MVC