Skip to content

唯一值

¥Unique Values

一般来说,Faker 方法不返回唯一值。

¥In general, Faker methods do not return unique values.

ts
faker.seed(55);
faker.animal.type(); //'cat'
faker.animal.type(); //'bird'
faker.animal.type(); //'horse'
faker.animal.type(); //'horse'

某些方法和语言环境使用的数据集比其他方法和语言环境小得多。例如,faker.animal.type 只有 44 种可能的动物可供选择。相比之下,faker.person.fullName() 从数百个名字、姓氏和前缀/后缀的列表中提取,因此它可以生成数十万个唯一的名称。即便如此,生日悖论 也意味着很快就会生成重复的值。

¥Some methods and locales use much smaller data sets than others. For example, faker.animal.type has only 44 possible animals to choose from. In contrast, faker.person.fullName() pulls from a list of hundreds of first names, surnames, and prefixes/suffixes, so it can generate hundreds of thousands of unique names. Even then, the birthday paradox means that duplicate values will quickly be generated.

有时,你想要生成唯一值。例如,你可能希望在数据库电子邮件列中具有唯一值。有几种可能的策略:

¥Sometimes, you want to generate unique values. For example, you may wish to have unique values in a database email column.\ There are a few possible strategies for this:

  1. 如果你想一次生成所有值,请使用 faker.helpers.uniqueArray()。例如:

    ¥Use faker.helpers.uniqueArray() if you want to generate all the values at one time. For example:

ts
faker.helpers.uniqueArray(faker.internet.email, 1000); // will generate 1000 unique email addresses
  1. 如果值不足以满足你的需求,请考虑使用你自己的顺序值作为前缀或后缀,例如,你可以依次将 1.2. 添加到每个生成的电子邮件的前缀。

    ¥If there are insufficient values for your needs, consider prefixing or suffixing values with your own sequential values, for example you could prefix 1., 2. to each generated email in turn.

  2. 构建你自己的逻辑来跟踪一组先前生成的值,并在生成重复值时根据需要重新生成值

    ¥Build your own logic to keep track of a set of previously generated values and regenerate values as necessary if a duplicate is generated

  3. 使用第三方包来强制唯一性,例如 enforce-unique@dpaskhin/unique

    ¥Use a third-party package to enforce uniqueness, such as enforce-unique or @dpaskhin/unique.

Faker v9.7 中文网 - 粤ICP备13048890号.