2

我有一个逻辑问题,我不确定 JavaScript 是否提供了一种特殊的方法来解决这个问题。在下面的简化测试代码中,我使用一个函数来创建一个随机数,并将它放入一个数组值中两次。我需要在两个地方使用相同的随机数,但显然如果我调用randomNumber()两次,我会得到两个不同的返回值。我知道我可以将返回值存储在一个变量中并多次调用该变量。但是 JavaScript 是否为此类问题提供了任何其他方法?

"use strict";

let myArray = [
    `Use a random number once here, ${randomNumber()}, and the same value again here ${randomNumber()}.`
];

function randomNumber() {
  return Math.random() * 10;
}

document.querySelector('.output').textContent = myArray[0];
<div class="output"></div>

4

2 回答 2

3

您可以将数组元素定义为返回所需字符串的 IIFE,并传入(单个)结果randomNumber()

"use strict";

let myArray = [
    ((rnd) => `Use a random number once here, ${rnd}, and the same value again here ${rnd}.`)(randomNumber())
];

function randomNumber() {
  return Math.random() * 10;
}

document.querySelector('.output').textContent = myArray[0];
<div class="output"></div>

于 2018-05-19T02:41:37.357 回答
1

使用发电机...

function *randomize(num = Math.random() * 10) {
  for (;;) yield num
}

let myNum = randomize(),
  myArray = [
    `Use a random number once here, ${myNum.next().value}, and the same value again here ${myNum.next().value}.`
  ];
于 2018-05-19T04:56:08.350 回答