js在遍历中使用Math.random()函数生成的数据是相同的,如何解决?

image.png
在这里el.expect和practical的值是相同的,怎么样让这两次随机数生成的值不同?
常试过的方法:抽出来分别写函数调用,结果还是相同的。

阅读 1.9k
2 个回答

你第二个push的也是expect,你看看

const randomInfo = (num) => {
  const expect = [];
  const practical = [];
  const stackedInfo = new Array(num).fill(null);

  stackedInfo.forEach((el, index) => {
    el = {};
    el.expect = (Math.random() * num).toFixed(2);
    expect.push(el.expect);

    do {
      el.practical = (Math.random() * num).toFixed(2);
    } while (el.practical === el.expect);

    practical.push(el.practical);
    stackedInfo[index] = el;
  });

  return stackedInfo;
};

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题