如何从数组中获取一定长度的随机单词?

时间:2018-01-15 22:23:06

标签: javascript arrays string random string-length

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

我目前能够从数组中得到一个随机字:

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

2 个答案:

答案 0 :(得分:1)

  

如何实现字长规范?

您可以随机循环拾取单词,除非长度符合您的要求,或者您保持按长度分组的单词(即多维数组)。然后你只需要选择正确的数组(你的var dT = require('doT'); var tpl = { tmpl:dT.template('{{=this.helper()}}'), helper: function(){ /* do what you want to do */ } } tpl.tmpl(); // render template )并按照目前的选择进行选择

答案 1 :(得分:0)

为什么不首先映射它然后应用你的电话?

// 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)];
相关问题