Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从数组中获取一定长度的随机字?_Javascript_Arrays_String_Random_String Length - Fatal编程技术网

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

Javascript 如何从数组中获取一定长度的随机字?,javascript,arrays,string,random,string-length,Javascript,Arrays,String,Random,String Length,我想从字符串数组中获得一个特定长度的随机字符串(由输入字段确定)。有没有办法不创建一个包含该长度的所有单词的新数组,然后从中进行选择 我目前可以通过以下方法从数组中随机获取一个单词: var word = arr[Math.floor(Math.random()*arr.length)]; 如何实现字长规范 您可以循环随机拾取单词,除非长度满足您的要求,或者您可以将单词按长度分组(即多维数组)。然后,您只需要选择正确的数组(您的arr)并像目前一样进行选择为什么不先映射它,然后应用调用呢 //

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

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

var word = arr[Math.floor(Math.random()*arr.length)];
如何实现字长规范


您可以循环随机拾取单词,除非长度满足您的要求,或者您可以将单词按长度分组(即多维数组)。然后,您只需要选择正确的数组(您的
arr
)并像目前一样进行选择

为什么不先映射它,然后应用调用呢

// 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.filter
originalArr.map(word=>word.length===requiredLength)
返回
[真、假、假、真]