我需要實作一個可以多次呼叫的 stringBuilder,對于第一次呼叫,stringBuilder 回傳一個應該存盤前一個值的函式,在其他呼叫中,它的回傳值取決于引數,如果沒有任何引數,則回傳一個字串它由所有先前的呼叫組成,但如果它有一個引數,它應該回傳一個新函式來存盤下一個字串,但每一步都應該能夠單獨呼叫。這是一個例子:
const stringBuilder = (str) => {
let result = str;
return (newStr) => {
if (typeof newStr == 'undefined') return result;
else {
result = newStr;
return stringBuilder(result)
}
}
}
const hello = stringBuilder('hello');
const helloWorld = hello(' world');
const helloWorldJS = helloWorld(' JS');
console.log(hello()); // I expect the result should be 'hello'
console.log(helloWorld()); // I expect the result should be 'hello world'
console.log(helloWorldJS());
任何幫助,將不勝感激。謝謝。
uj5u.com熱心網友回復:
您不需要將先前的值存盤在result變數中,您可以使用新字串連接先前的字串并再次呼叫stringBuilder,如下所示:
const stringBuilder = (str)=> {
return (newStr)=> newStr ? stringBuilder(str newStr) : str;
}
const hello = stringBuilder('hello');
const helloWorld = hello(' world');
const helloWorldJS = helloWorld(' JS');
const helloWorldStackoverflow = helloWorld(' stackoverflow');
console.log(hello());
console.log(helloWorld());
console.log(helloWorldJS());
console.log(helloWorldStackoverflow());
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402453.html
標籤:
下一篇:DAPP應用場景
