gpt4 book ai didi

javascript - 如何从数组中的一个对象的属性返回该对象?

转载 作者:行者123 更新时间:2023-12-03 04:15:19 24 4
gpt4 key购买 nike

我有一个对象数组,我正在尝试弄清楚如何通过其名称的属性返回对象。

这是测试:

describe("Classroom", function() {
var classroom, jalil, irene, kelvin, myra;

beforeEach(function() {
// Define student objects
jalil = new Student({firstName: "Jalil", scores: [100, 100]});
irene = new Student({firstName: "Irene", scores: [95, 95]});
kelvin = new Student({firstName: "Kelvin", scores: [94, 94]});
myra = new Student({firstName: "Myra", scores: [70, 70]});

// Assign classroom
classroom = new Classroom([jalil, irene, kelvin, myra]);
});

这是我尝试过的:

Classroom.prototype.find = function(name) {
var index = this.students.indexOf(name);
return this.students.splice(index, 1);
};

它没有通过,似乎正在返回数组内的一个对象。谁能解释一下为什么?

最佳答案

是的,没有找到,因为

this.students.indexOf(name);

name{firstName: "Jalil", Scores: [100, 100]} 等对象进行比较。

您需要使用Array.prototype.filter如果您想返回所有找到的项目:

Classroom.prototype.find = function(name) {
return this.students.filter((o)=>{
return o.firstName === name;
});
};

或者Array.prototype.find如果您只想返回第一个找到的项目:

Classroom.prototype.find = function(name) {
return this.students.find((o)=>{
return o.firstName === name;
});
};

关于javascript - 如何从数组中的一个对象的属性返回该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164668/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com