【问题标题】:How do i make something random in a function?我如何在函数中随机制作一些东西?
【发布时间】:2020-05-29 21:54:13
【问题描述】:

我有一个函数,里面有一些图像:

function rain() {
    ctx.drawImage (image1, x, y, 100, 50);
    ctx.drawImage (image2, x, y, 100, 50);
    ctx.drawImage (image3, x, y, 100, 50);
    ctx.drawImage (image4, x, y, 100, 50);
}

如何让这个函数在调用时随机选择其中一张?

【问题讨论】:

标签: javascript function random


【解决方案1】:

你应该把你的图片放在一个数组中,然后选择一个随机的数组索引。

function randomImage() {
  const images = [
    image1,
    image2,
    image3,
    image4,
  ];
  // Pick an index at random from the images array. Math.rand returns
  // a random number between 0 and 1, multiplying that by the length
  // of the images array, gets a number between 0 and the length of the
  // array, and flooring it makes it into an integer.
  const randomIndex = Math.floor(Math.rand() * images.length);
  return images[randomIndex];
}

【讨论】:

    【解决方案2】:

    当我想处理随机性时,我认为做数学很不方便,所以我使用Rando.js 来使这样的东西简单易读。

    var images = ["one", "two", "three", "four"];
    
    console.log( rando(images).value );
    <script src="https://randojs.com/1.0.0.js"></script>

    如果你想使用这段代码,你只需要知道script标签来源于rando函数,你就可以马上使用了。只需将脚本标签放在 HTML 文档的头部即可。这很简单,但如果您需要了解更多信息,可以查看 websitegithub repo 上的示例。

    【讨论】:

    • 或者不用为此导入第三方脚本,您可以简单地构建自己的...const rando = arr => arr[Math.floor(Math.random() * arr.length)]
    • 是的,你完全可以,但另一个答案已经解决了这种方法,所以我想我会添加一些新的东西。它绝对不是一个必不可少的库,但不必考虑数学是一个很好的便利。另外,无论如何它都非常小(2.1kb),它可以处理每种类型的值加上 jquery 元素来做几乎任何你需要的事情。如果你想保持本地化,你可以直接从randojs.com/1.0.0.js 复制脚本到你的项目中。这是一种偏好。有些人喜欢看到他们所做的事情背后的数学原理,有些人则不喜欢
    猜你喜欢
    • 2017-10-14
    • 2011-12-09
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    • 2011-09-07
    • 2011-06-26
    • 2012-04-27
    • 1970-01-01
    相关资源
    最近更新 更多