如何从 yield* 获取当前字符串的长度

How do I get the length of the current string, from a yield*

我发布了这个问题:

接受的答案有一些非常巧妙的代码,但我在理解它时遇到了一些问题。
本质上,如果我问出来的字符串长度,它总是和它能输出的最大长度一样长。

我猜是产量*确实给我带来了一些问题。
在阅读 yield* 时,它确实说它考虑了最终值。
因此,我更改了以下代码以突出显示我的问题。

(async function() {
   for(const combo of combinations(5)) {
     console.log(combo.length + "\t" + combo);
     await timer(1);
   }
})();

输出结果如下:

5      !
5      "
5      #
5      $
5      %
5      &
5      '
5      (
5      )
5      *
5      +
5      ,
5      -
5      .
5      /
5      0
5      1
5      2
5      3
5      4
5      5
5      6
5      7
5      8
5      9
5      :
5      ;

即使字符串只有 1 个字符,它仍然声称它是 5 个。
那么,如何从生成器中获取实际值的长度?

正在获取实际值的长度。这里发生了两件事:

首先,他们给你的代码只输出长度为 5 的字符串(或传入的任何数字),而不是你要求的长度递增的字符串。也就是说,他们给你的代码不符合你的要求。如果你想保留生成器方法,这里有一些代码将输出所有长度为 1-5 的字符串,但我不确定它是否符合你想要的顺序:

function* combinations(length, previous = "") {
  for(const char of chars())
    yield previous + char;

  if (length > 1) {
    for (const char of chars())
      yield* combinations(length - 1, previous + char)
  }
}

其次,字符串 看起来 少于 5 个字符的原因是在可打印字符之前有不可打印的字符,而您只能看到可打印的字符。例如,算法将使用的第一个字符是 String.fromCharCode(0),并且该字符不可打印。

const unprintable = String.fromCharCode(0);
console.log(unprintable);
console.log(JSON.stringify(unprintable));

const longer = unprintable + '!'
console.log(longer);
console.log(JSON.stringify(longer));
console.log(longer.length);