javascript - 有没有办法让事件总时间始终为24小时

标签 javascript arrays object

我想随机生成某人每天花在各种事件上的小时数。

我创建了一个对象,该对象将存储对象键(事件)、其值(小时)以及一个用于存储它们的数组。我还使用随机方法生成小时数,并确保每个初始值在随机生成下一个对象属性之前不超过 24 小时。但我需要总和为 24 小时的小时数。

 let organised = new Object(),
    pworks = null,
    commutes = null,
    fun = null,
    work = false;
    let arr= [];
   if(!work){ 
       organised.pworks = Math.floor(Math.random()*24)
       if(organised.pworks < 24){
           console.log('you spend ' + organised.pworks+'hrs' + ' on Primary Work' )
          arr.push(organised.pworks)
          organised.commutes = Math.floor(Math.random()*24)
          if(organised.commutes + organised.pworks < 24){
            arr.push(organised.commutes)
            console.log('you spend ' + organised.commutes+'hrs' + ' on Commute' )
            organised.fun = Math.floor(Math.random()*24)
            if(organised.commutes + organised.pworks + organised.fun <= 24){
            console.log('you spend ' + organised.fun+'hrs' + ' on having Fun' )
    arr.push(organised.fun)
  }
}

} }

您在主要工作上花费了 6 小时 您在通勤上花费了 10 小时 你花了 8 小时来享受乐趣

最佳答案

您需要在剩余时间内随机选择随机值,而不是完整的 24 小时。例如,这是不正确的:

organised.commutes = Math.floor(Math.random() * 24);

...因为它不允许 organized.pworks 占用的时间。所以:

organised.commutes = Math.floor(Math.random() * (24 - organized.pworks));

...下一个依此类推,它必须允许 organized.pworksorganized.commute。保持运行记录可能会很方便,这样您就不必继续添加更多属性:

var remaining = 24;
organised.pworks = Math.floor(Math.random() * remaining);
remaining -= organised.pworks;
// ...
organised.commutes = Math.floor(Math.random() * remaining);
remaining -= organised.commutes;
// ...

那么您可能不需要最后一个随机值,您只需要剩余时间:

organised.fun = remaining;

关于javascript - 有没有办法让事件总时间始终为24小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079325/

相关文章:

javascript - 将音频播放限制在指定范围内

javascript - 函数表达式到底发生了什么?

javascript - 在 JavaScript 中过滤字符串数组的最快方法

python - 使用 pandas 的 Silhouette_score 的正确数据格式

python - 我无法理解类 <classname>(unicode) : in Python?

javascript - 当我再次调用 Canvas 时如何删除以前的 Canvas 形状?

javascript - 尝试 .replace() 但没有成功

Java 8 - 如何将数组列表转换为特定类对象的列表

javascript - 将数组的数组作为项目转换为以对象作为项目的对象

javascript - 如何处理多个数值数据集进行计算?