创建一个函数,该函数接受人员对象数组,并从该数组中返回第一个找到的宇航员对象。
这是我创建的代码;
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people.astronaut[i] === false) {
return null
}
else if (people.astronaut[i]) {
return people[i]
}
}
我的代码针对此测试运行;
describe("findFirstAstronaut", () => {
it("returns null if no Astronaut is in the array", () => {
expect(findFirstAstronaut([])).to.be.null;
});
it("returns a person object who is an astronaut", () => {
const astronaut = { name: "Tim Peake", isAstronaut: true };
expect(findFirstAstronaut([astronaut])).to.have.keys([
"name",
"isAstronaut"
]);
expect(findFirstAstronaut([astronaut]).isAstronaut).to.be.true;
});
it("returns the first astronaut from the array", () => {
const astronauts = [
{ name: "Johnny Karate", isAstronaut: false },
{ name: "Neil Armstrong", isAstronaut: true },
{ name: "Valentina Tereshkova", isAstronaut: true },
{ name: "Bert Macklin", isAstronaut: false },
{ name: "Eileen Collins", isAstronaut: true },
{ name: "Kip Hackman", isAstronaut: false }
];
expect(findFirstAstronaut(astronauts)).to.eql({
name: "Neil Armstrong",
isAstronaut: true
});
});
});
如何修复我的代码?
答案 0 :(得分:6)
如果您可以选择ES6,则ES6引入了一种新的方法来实现这一目标:
myArray.find(item => {
return item.isAstronaut
})
或更缩写:
myArray.find(item => item.isAstronaut)
find()
是新的迭代器之一,它与filter()
和map()
以及其他迭代器一起可以更轻松地处理数组。 find()
将返回数组中符合条件的第一项。 =>
或“箭头功能”意味着您无需显式包括return语句。
答案 1 :(得分:3)
您需要为数组使用索引。
people[i] // for the object people[i].isAstronaut // for a property of the object
然后,您只需要检查isAstronaut
是否为true
并随物品一起返回即可。
在for
循环的末尾,返回null
,以寻找一名找不到的宇航员。
如果您在循环内进行检查,则返回错误的结果将为时过早。
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
答案 2 :(得分:2)
一支班轮
arr.filter(item => item.isAstronaut)[0]
答案 3 :(得分:0)
您可以使用isAstronaut
过滤掉具有Array.prototype.filter
属性等于false的数组元素。我不喜欢filter
胜过Array.prototype.find
,因为并非所有浏览器都支持ES6。
有了过滤后的数组后,只需将元素放在0
索引位置即可。如下所示:
const astronauts = [{
name: "Johnny Karate",
isAstronaut: false
},
{
name: "Neil Armstrong",
isAstronaut: true
},
{
name: "Valentina Tereshkova",
isAstronaut: true
},
{
name: "Bert Macklin",
isAstronaut: false
},
{
name: "Eileen Collins",
isAstronaut: true
},
{
name: "Kip Hackman",
isAstronaut: false
}
];
//Array destructuring to get the first astronaut:
var [firstAstronautFound] = astronauts.filter(el => el.isAstronaut);
//Line above is same as doing this:
//var firstAstronautFound = astronauts.filter(el => el.isAstronaut)[0];
console.log(firstAstronautFound.name);
答案 4 :(得分:0)
首先,您可能需要检查数组中是否有任何项目,否则返回null。
第二,您必须检查属性
第三,您必须检查属性isAstronaut的值
function findFirstAstronaut(people) {
if (people.length > 0)
{
for (let i = 0; i < people.length; i++) {
if (("name" in people[i]) && ("isAstronaut" in people[i])) {
if (people[i].isAstronaut)
return people[i];
else
return true;
}
}
}
else
return null;
}