【问题标题】:How do I get the length of the current string, from a yield*如何从 yield* 获取当前字符串的长度
【发布时间】:2019-05-12 13:38:23
【问题描述】:

我发布了这个问题:How to generate all possible strings, with all ascii chars, to a certain length

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

我猜是 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 个。
那么,如何从生成器中获取 ACTUAL 值的长度?

【问题讨论】:

    标签: javascript node.js ecmascript-6 generator yield


    【解决方案1】:

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

    首先,他们给你的代码只输出长度为 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);

    【讨论】:

    • 这就是为什么在有疑问时应该打印字符串 console.log(JSON.stringify('\x00')); 而不是字符串的表示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 2011-07-14
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    相关资源
    最近更新 更多