简体   繁体   English

Faker.js 带有选择的随机词

[英]Faker.js random word with choices

I'm trying to use faker.js to generate some random words, but I want it to choose between a few choices.我正在尝试使用 faker.js 生成一些随机单词,但我希望它在几个选项之间进行选择。

faker.random.word()

I tried something like this我尝试过这样的事情

faker.random.word({constraints: ['','','']})

This didn't work, and I could be way off since this was just a straight up guess.这没有用,我可能会离开,因为这只是一个直接的猜测。 I tried looking for documentation on it but couldn't find any.我尝试查找有关它的文档,但找不到任何文档。 Any suggestions?有什么建议么?

You can generate a number between 0 and the number of words you have and access the words using an array您可以生成一个介于 0 和您拥有的单词数之间的数字,并使用数组访问这些单词

const words = ["foo", "bar", "baz"]
const randomNumber = faker.datatype.number({
    'min': 0,
    'max': words.length - 1
});
console.log(words[randomNumber])

I have not seen anything like this in faker module but you can using uniqueNamesGenerator module, check the documentation我在 faker 模块中没有看到这样的东西,但你可以使用uniqueNamesGenerator模块,查看文档

const { uniqueNamesGenerator } = require('unique-names-generator'); ;
 
const colors = [
  'Green', 'Red', 'Yellow', 'Black'
]
 
const characterName =  uniqueNamesGenerator({
  dictionaries: [colors],
  length: 1
});

console.log(characterName)

i was looking for same issue in php, the php way is this:我在 php 中寻找同样的问题,php 方法是这样的:

echo $faker->randomElements(['a', 'b', 'c', 'd', 'e']);

['c'] ['C']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM