【问题标题】:How do I get a random word of a certain length from an array?如何从数组中获取一定长度的随机单词?
【发布时间】:2018-01-15 22:23:06
【问题描述】:

我想从字符串数组中获取一定长度(由输入字段确定)的随机字符串。有没有办法做到这一点,而不创建一个包含该长度的所有单词的新数组然后从中选择?

我目前可以通过以下方式从数组中获取一个随机单词:

var word = arr[Math.floor(Math.random()*arr.length)];

【问题讨论】:

    标签: javascript arrays string random string-length


    【解决方案1】:

    如何实现字长规范?

    除非长度满足您的要求,或者您将单词按长度分组(即多维数组),否则您会随机循环选取单词。然后你只需要选择正确的数组(你的arr)并像你目前所做的那样选择

    【讨论】:

      【解决方案2】:

      为什么不先映射它然后应用你的调用?

      // Example: 
      const requiredLength = 5,
      const originalArr = ['lalal', 'hehehehehe', 'uhuhuhuh', 'uooou'];
      
      const arr = originalArr.map(word => word.length === requiredLength);
      // arr = ['lalal','uooou'];
      
      const word = arr[Math.floor(Math.random()*arr.length)];
      

      【讨论】:

      • 您的意思是Array.filteroriginalArr.map(word => word.length === requiredLength); 返回[true, false, false, true]
      猜你喜欢
      • 1970-01-01
      • 2013-06-13
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多