最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Faker.js random word with choices - Stack Overflow

programmeradmin6浏览0评论

I'm trying to use faker.js to generate some random words, but I want it to choose between a few choices.

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?

I'm trying to use faker.js to generate some random words, but I want it to choose between a few choices.

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?

Share Improve this question asked Feb 4, 2021 at 17:48 terntternt 311 silver badge3 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

Since Faker v6.3.0, the following 2 methods should do the trick:

  1. faker.helpers.arrayElement (doc)
  2. faker.helpers.arrayElements (doc)

You can generate a number between 0 and the number of words you have and access the words using an array

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

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 :

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

['c']

发布评论

评论列表(0)

  1. 暂无评论