我需要一次從字串中洗掉一個字符,而不使用本機方法或回圈。我已經找到了無數方法來做到這一點,而無需本地方法或沒有回圈,但似乎無法找到沒有任何方法的方法。我能夠想出一種使用遞回來避免回圈的方法,但不確定如何不使用 string.slice() 方法。我必須使用遞回。不,這不是作業問題,我只是在練習面試。
該函式應該計算目標字符在輸入字串中重復(如果有的話)的次數。
const countChar = (input, target) => {
if (input === '') return 0;
if (input[0] === target) return 1 countChar(input.slice(1), target);
return countChar(input.slice(1), target);
}
console.log(countChar('hello world', 'o')); // 2
console.log(countChar('javascript', 'j')); // 1
uj5u.com熱心網友回復:
您當前代碼使用的主要內容.slice()是“修剪”您的字串,以便在下一次遞回呼叫中,您input的第一個字符是您需要檢查的下一個字符。相反,您可以傳遞要檢查的當前字符的索引,從而避免slice呼叫:
const countChar = (input, target, i = 0) => {
if (i >= input.length) return 0;
if (input[i] === target) return 1 countChar(input, target, i 1);
return countChar(input, target, i 1);
}
console.log(countChar('hello world', 'o')); // 2
console.log(countChar('javascript', 'j')); // 1
當然還有其他方法.slice()可以用來分解字串,但這些方法仍然涉及“回圈”/在引擎蓋下迭代字串。一個例子是解構:
const countChar = ([c, ...rest], target) =>
c ? (c === target) countChar(rest, target) : 0;
console.log(countChar('hello world', 'o')); // 2
console.log(countChar('javascript', 'j')); // 1
console.log(countChar('', 'j')); // 0
上面的代碼片段使用解構??賦值 從傳遞給函式的第一個引數[c, ...rest]中提取第一個字符(存盤在 中)。c獲取傳入字串中的...rest所有字符(不包括提取的第一個字符)并將其存盤在變數中rest。
然后使用條件運算子 ? :檢查變數c是否具有真值(即:有效字符)。當傳遞一個空字串時,c將持有一個虛假值(undefined在我們的例子中) 。countChar()如果c為真,則它持有一個有效的字符值,因此將 的結果(c === target) countChar(rest, target)用作函式呼叫的回傳值。
這里(c === target)將評估為trueor false,當使用 with 時 countChar(rest, target)將布林值轉換為數值,1如果它是true,或者0如果它是false。當: 0;是假值0時用作回傳值c的方法(即:沒有更多字符需要檢查)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/430688.html
標籤:javascript 递归
