gpt4 book ai didi

Javascript: 递归问题 --> 返回深度嵌套对象中最长的键值

转载 作者:行者123 更新时间:2023-11-29 20:41:20 25 4
gpt4 key购买 nike

下面是问题:

//获取最长的名字

//编写一个函数,getLongestName,接受一个对象。该对象代表一棵家谱。返回家族中最长的名字。

这是代码,但返回错误:

let family = {
'Beverly Marquez': {
'Nina Rhone': {
'William Rhodes': null,
'Paul Nell': null,
'Sir Paddington the Fourth, of the county Wilstonshire': null
}
}
};


function getLongestName (family){

let longestName = '';

for (let key in family){
let value = family[key]
console.log(value)

if (typeof value === 'object'){
let descendentLongestName = getLongestName (value)
}

else {
descendentLongestName = value
}

if (descendentLongestName.length > longestName.length){
let longestName = descendentLongestName
}
}
return longestName;
}


getLongestName(family); // => 'Sir Paddington the Fourth, of the county Wilstonshire'

当我运行上面的代码时,出现以下错误:ReferenceError: descendentLongestName is not defined

我做错了什么?

最佳答案

我不知道如何修复您的代码,但我想建议一个新的解决方案。

我们的想法是将您的问题分解为两部分:

  • 递归地从嵌套对象中找到所有键
  • 从一组字符串中找出最长的一个

let longest = ary => ary
.reduce((max, x) =>
x.length > max.length ? x : max, '');

let allKeys = obj => obj
? Object.keys(obj).concat(
...Object.values(obj).map(allKeys))
: [];

//

let family = {
'Beverly Marquez': {
'Nina Rhone': {
'William Rhodes': null,
'Paul Nell': null,
'Sir Paddington the Fourth, of the county Wilstonshire': null,
}
}
};

console.log(longest(allKeys(family)));

关于Javascript: 递归问题 --> 返回深度嵌套对象中最长的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55459771/

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