对象数组:建议通过对象键或数组索引或数组项本身选择特定的项?



我正在处理类对象的数组[]。要求使用该对象数组来记住当前选择的对象。例如,我有一个名为Person的类,而contactsvar 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;

所以我想让用户从contact列表中选择任何person,所以我使用<select><option>让用户允许选择任何Person,这意味着我使用Personname道具,所以我现在从用户选择中获得Personname,当用户选择或做任何需要与Person的对象交互的事情时,或者使用它为用户做一些计算并显示结果。

我可以在<select>上使用onChange事件

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

哪个是更好的方法,为什么?

还有其他更有效的方法吗?

请分享你对这个问题的看法。

如果namePerson对象的数组中是唯一的,并且该数组不是真正的庞大(如果它馈送到option元素中,则不会如此),那么您所做的是很好的。如果数组内容发生变化,使用name而不是数组索引也更加健壮。

您可以考虑使用Map而不是数组:

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()) {
// ...
}

可以使用Map类:

const people = new Map()
people.set('Jane', new Person('Jane'))
people.set('John', new Person('John'))
people.has('Jane') // true
people.has('Jack') // false
console.log(people.get('Jane'))

最新更新