|
发表于 2024-4-16 11:37:18
|
显示全部楼层
非常抱歉我之前的回答依然有误。以下是正确的实现:
- function findOutermostKey(dictionary, targetKey) {
- let outermostKey = null;
- function findKeyInNestedDict(nestedDict, targetKey) {
- for (let key in nestedDict) {
- if (key === targetKey) {
- return true;
- }
- if (typeof nestedDict[key] === 'object') {
- const found = findKeyInNestedDict(nestedDict[key], targetKey);
- if (found) {
- outermostKey = key;
- return true;
- }
- }
- }
- return false;
- }
- findKeyInNestedDict(dictionary, targetKey);
- return outermostKey;
- }
- // 示例用法
- const myDict = {
- a: {
- b: {
- c: 'value'
- },
- d: 'another value',
- },
- e: {
- f: 'yet another value',
- },
- g: 'final value'
- };
- const result = findOutermostKey(myDict, 'c');
- console.log(result); // 输出 'a'
复制代码
在这个示例中,我们定义了一个递归函数 `findKeyInNestedDict`,它的参数是嵌套字典 `nestedDict` 和目标键值 `targetKey`。函数首先遍历 `nestedDict` 的每一个键值对,如果当前键等于目标键,则返回 `true`。如果当前值是一个嵌套的字典,则递归调用函数进行查找。当递归返回 `true` 时,表示找到了目标键,并通过设置 `outermostKey` 为当前键来记录最外层键。最终返回最外层键。
希望这次的回答能够满足您的需求!如果还有任何问题,请随时提出。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|