【问题标题】:Faker shows the same picture all the time, how to avoid it?Faker老是显示同一张图,如何避免?
【发布时间】:2018-03-29 23:58:29
【问题描述】:

我正在使用 faker 来制作随机对象数组,如下所示:

{
  "image":  faker.random.arrayElement([
    faker.image.nature(), 
    faker.image.city(), 
    faker.image.food() 
  ]),
  "price": faker.random.number({ min: 20, max: 300 }),
  "beds": faker.random.number({ min: 1, max: 15 }),
  "type": faker.random.arrayElement([ 
    "Entire home", 
    "Private room", 
    "Shared room" 
  ])
}

实际上,当制作 12 个这样的元素时会发生什么 - 所有数据都是随机的,但不是图像,每次加载都是一样的。

每次刷新都有其他照片,但数组中的所有元素都包含相同的图像。

我该怎么办?

【问题讨论】:

    标签: javascript json npm faker


    【解决方案1】:

    准确地说,faker.js 返回的是相同的 url,例如http://lorempixel.com/640/480/nature 用于 faker.image.nature() 调用,因为它是 lorempixel.com 服务,可根据请求返回随机图像。

    如果您希望看到完全相同的图像,那么这可能与您的浏览器缓存响应有关(如果是这样,请尝试在开发过程中禁用缓存或向图像添加随机查询字符串,例如'image': `${faker.image.nature()}?random=${Date.now()}`) .

    所以回答你的问题 - 你不需要做任何事情。您最终会得到随机图像(根据 lorempixel.com 的要求)。

    【讨论】:

    • 我实际上选择了${faker.image.nature()}?random=${Math.round(Math.random() * 1000)} 以获得更多随机性
    • 这样可以提供更精确的输出
    猜你喜欢
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    相关资源
    最近更新 更多