如何在不使用 Javascript 中的本机方法或循环的情况下从字符串中删除字符?

How to remove a character from a string without using native methods nor loops in Javascript?

我需要一次从字符串中删除一个字符,而不使用本机方法或循环。我已经找到了无数种无需本机方法或无需循环即可执行此操作的方法,但似乎找不到一种方法可以做到这一点。我能够想出一种使用递归来避免循环的方法,但不确定如何不使用 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

当前代码使用 .slice() 的主要目的是将字符串“trim”向下,以便在下一次递归调用时 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

上面的代码片段使用 destructuring assignment [c, ...rest] 从传入函数的第一个参数中提取第一个字符(存储在 c 中)。 ...rest 从传入的字符串中获取所有字符(不包括提取的第一个字符)并将其存储在变量 rest.

conditional operator ? : is then used to check if the variable c has a truthy value (ie: a valid character). c will hold a falsy value (在我们的例子中是 undefined )当 countChar() 被传递一个空字符串。如果 c 为真,则它包含一个有效的字符值,因此 (c === target) + countChar(rest, target) 的结果用作函数调用的 return 值。

此处 (c === target) 将计算为 truefalse,当与 + countChar(rest, target) 一起使用时将布尔值转换为数值,1如果是 true,或者 0 如果是 false: 0; 表示 0 用作 return 值,而 c 是一个假值(即:没有更多字符需要检查)。