javascript - 从数组中创建 N 位随机单词

我想从这个数组中创建一个 4 位随机单词。

const words = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'k'];

为此我这样编码......

const word = (
    words[Math.floor(Math.random() * 9)] +
    words[Math.floor(Math.random() * 9)] +
    words[Math.floor(Math.random() * 9)] +
    words[Math.floor(Math.random() * 9)]
    );
console.log(word) // afab

为此,如果我需要 6 位或 10 位,我需要再次重复代码 words[Math.floor(Math.random() * 9)]

如何使用易于生成N位随机词的变量编写代码而不重复代码?

提前致谢

最佳答案

你可以利用Array.from 得到length 长度的单词

Array.from({ length }, () => arr[Math.floor(Math.random() * arr.length)]).join("")

使用创建动态长度

arr.length  // instead of 9(Don't hardcode)

const words = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k"];

function generateRandomWord(arr, length) {
  return Array
          .from({ length },() => arr[Math.floor(Math.random() * arr.length)])
          .join("");
}

console.log(generateRandomWord(words, 4));
console.log(generateRandomWord(words, 8));
console.log(generateRandomWord(words, 12));

https://stackoverflow.com/questions/69960532/

相关文章:

python - 如何根据字典键和值过滤 Pandas 数据框行?

javascript - 如何使用 "onclick"方法获取数据属性?

javascript - 如何在 react-native 中结合使用 Drawer Navigat

awk - 使用 grep 或 awk 查找 txt 和 csv 文件之间的匹配行

typescript - @typescript-eslint/naming-convention

haskell - 如何使用 `zipTree` 实现 `foldTree` ?

flutter - 无法将类型为 'String' 的值分配给 flutter Getx 中类型为

intellij-idea - 如何将项目从 IDEA 连接到 Gitlab

javascript - 带有 Material-UI 的 SSR 上的@emotion/cache

perl - 从包含日期的文件中排序并提取一定数量的行