假設我有這樣的輸入物件:
const obj = {
deep: {
someKey: 'someValue1!',
veryDeep: {
someOtherKey: 'someOtherValue'
}
},
deep2: {
aa: 'bba'
}
}
我想撰寫一個函式,將這個物件作為第一個引數,將鍵字串作為第二個引數。然后它將通過遞回回圈遍歷 obj 并找到值并回傳它。所以如果我命名這個函式getObjectValueOfKey,它會被這樣呼叫:getObjectValueOfKey(obj, 'aa')它會回傳'bba'.
我想我很接近這段代碼:
const getObjectValueOfKey = (obj, key) => {
const keys = Object.keys(obj)
for (let currKey of keys) {
if (typeof obj[currKey] === 'object') {
getObjectValueOfKey(obj[currKey], key)
}
if (currKey === key) {
return obj[key]
}
}
}
const res = getObjectValueOfKey(obj, 'aa')
console.log('res', res)
但由于一些我不知道的原因res是undefined。
uj5u.com熱心網友回復:
你非常接近,遞回很好,但問題與你的代碼中的所有路徑都沒有回傳有關,實際上唯一回傳的路徑是當你在物件的第一級找到密鑰之后,你做了遞回并找到結果但沒有回傳任何內容,代碼到達函式的末尾并且javascript默認回傳未定義如果沒有找到任何回傳,解決問題決定將遞回中找到的結果存盤在變數中并在函式結束時回傳該值。
const getObjectValueOfKey = (obj, key, found) => {
const keys = Object.keys(obj);
let result = undefined;
result ||= found;
for (let currKey of keys) {
if (typeof obj[currKey] === "object") {
result ||= getObjectValueOfKey(obj[currKey], key, result);
}
if (currKey === key) {
return obj[key];
}
}
return result;
};
const res = getObjectValueOfKey(obj, "aa", undefined);
console.log("res", res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/422787.html
標籤:
上一篇:超過LeetCode40時間限制
