【发布时间】:2020-10-23 02:25:37
【问题描述】:
我正在尝试编写一个函数来查找一个人的后代。我拥有的数据设置在一个数组中,格式如下:
{
"id": 159819275,
"firstName": "Jasmine",
"lastName": "Bob",
"gender": "female",
"dob": "12/18/1969",
"height": 58,
"weight": 156,
"eyeColor": "blue",
"occupation": "assistant",
"parents": [409574486, 260451248],
"currentSpouse": 951747547
},
我编写的函数接受我正在寻找其后代的人的 ID、人员数组,并创建一个包含后代的新数组。
function findDescendants (id, people, descendantsArray = []){
descendantsArray = people.filter(function(el){
return el.parents[0] === id || el.parents[1 === id] //id works if it's a variable, but if it's a array it won't work. otherwise function is good
})
displayPeople(descendantsArray) //calls a method that alerts the descendant's names into a string
id = []; //resets the id and turns it into an array
for(let i = 0; i<descendantsArray.length; i++){
id[i] = descendantsArray[i].id
} //puts the id's of the listed descendants into the array id
if (descendantsArray.length === 0){
return descendantsArray;
}
else {
findDescendants(id, people, descendantsArray)
} //sends in the array id, the data set people, and the descendantsArray (which contains the children of the person in question.
}
我的问题是,当我第二次调用数组时,过滤器不会将 el.parents 与 id 中的所有元素进行比较,我不知道从哪里开始。
descendantsArray = people.filter(function(el){
return el.parents[0] === id || el.parents[1 === id] //id works if it's a variable, but if it's a array it won't work. otherwise function is good
})
我希望这个语句做的是过滤掉那些“父母:”包含id数组中的任何元素的人中的所有元素。任何帮助将不胜感激。
【问题讨论】:
-
el.parents[1 === id]你可能是这个意思?el.parents[1] === id
标签: javascript arrays recursion filter dataset