javascript - 蛇形穿过 Javascript 数组

标签 javascript arrays node.js distribution discord

这可能是一个简单的答案,但我是一个最有兴趣的人,这真的让我伤透了脑筋。我正在尝试通过遍历数组来为变量赋值。

我的代码是用 Discord.js 编写的用于 Discord 的 TTRPG 工具机器人。对于此特定功能,我想让它根据输入的玩家数量滚动 n 个统计数据,然后将所有这些数据集中在一起并进行排序。从那里开始,我想让它蜿蜒穿过排序数组,为每个玩家提供一个统计数据集,以便每个玩家都尽可能接近公平的竞争环境。

例如,如果输入是 3 名玩家,则机器人将滚动 3 组 6 项统计数据并将它们汇集到一个数组中。为了便于解释,我们假设我们将所有数字从 1 到 18 滚动。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

将被分配给

A B C C B A A B C C B A A B C C B A

这样最终的变量就会

A = [1, 6, 7, 12, 13, 18]

B = [2, 5, 8, 11, 14, 17]

C = [3, 4, 9, 10, 15, 16]

我现在拥有的代码仅通过循环(A、B、C、A、B、C...)对它们进行排序,这不会导致玩家被平均。我已经尝试了很多不同的方法来获得我需要的结果,但是要么只对结束变量赋值一次,让中间变量分配更多的统计数据,要么只为每个玩家变量分配一个统计数据。

我曾尝试在网上搜索任何帮助,但使用“Javascript”和“Snake”谷歌搜索任何东西都只是教你如何制作游戏,所以我真的希望你们能帮助我。非常感谢你,如果我想说的不清楚,我很抱歉,所以我非常乐意回答你可能需要帮助解决这个问题的任何问题!

代码:

if (msgContent.startsWith(".dstats ")) {
  let args = msgContent.split(" ").slice(1);
  var regex = /^\d+$/;
  var statIndex = [];
  var reply;
  var forward = true;
  if(regex.test(args) && args <= 10){
    for(var i = 0; i < args*6; i++){
      statRoll();
      statIndex.push(randStat);
    };
    distSort = statIndex.sort(sortNumber);
    for( j = 0; j < args; j++){
      this['player'+j] = [];
    };
    var playIndex = 0;
    for( f = 0; f < distSort.length; f++){
      if(playIndex < args && playIndex >= 0){
        this['player'+playIndex].push(distSort[f]);
      }else {
        playIndex = 0;
        this['player'+playIndex].push(distSort[f]);
      };
      playIndex++;

    };
    reply = "Your stats blocks are as follows:\n";
    for (k = 0; k < args; k++){
      reply += "Player " + (k+1) +": [" + this['player'+k].join(', ') + "]\n";
    };
    msg.reply(reply);
  }else(
    msg.reply("Looks like you inputted an improper number or your number is too high. Check your command and try again!")
  );
}

最佳答案

在这种情况下,我建议尽可能使用 JSON,因为它会使处理数据变得更加容易。

无论如何,下面的代码应该可以解决问题:https://jsbin.com/quvexu/edit?js,console

// Declare input and output variables
arr1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
arr2 = ['a','b','c','c','b','a','a','b','c','c','b','a','a','b','c','c','b','a'];
results = {a:[], b:[], c:[]};

// Do the work
arr2.forEach(function(d,i){ results[d].push(arr1[i]); })

// Print the results 
console.log("Results", results);

关于javascript - 蛇形穿过 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42488387/

相关文章:

javascript - 更改工具提示颜色 d3.js

c - 使用 scanf 定义 malloc 数组大小并初始化

javascript - 如何在 Ember 或 Jquery 中重新加载页面

javascript - 设置从 URL 中选择多个

javascript - 如果选中复选框,则显示或隐藏表格行

java - 在 jooq 中使用数组参数调用 postgres 函数

java - 返回 int[][] 数组

javascript - AWS Lambda JavaScript SDK 异步处理程序

javascript - 我应该在 XMLHttpRequest 中使用什么回调函数来呈现响应?

javascript - 如何动态更改 div 的高度以匹配包含它的 div 的大小