首页 > 解决方案 > 为什么数组的相应部分在我的代码中不匹配?

问题描述

我正在做一个项目,其中我有三个数组,一个数组中的一个元素对应于其他数组中具有相同索引的元素。我通过生成一个随机数来找到一个数组的随机元素,但是当我在以该随机数为索引的数组中搜索元素时,它们不对应。我怎样才能使它们对应?

var qbNames = ['Patrick Mahomes', 'Lamar Jackson', 'Russell Wilson', 'Deshaun Watson', 'Drew Brees', 'Aaron Rodgers', 'Ryan Tannehill', 'Kyler Murray', 'Carson Wentz', 'Matt Ryan', 'Dak Prescott', 'Philip Rivers', 'Tom Brady', 'Ben Roethlisberger', 'Josh Allen', 'Matthew Stafford', 'Kirk Cousins', 'Cam Newton', 'Jared Goff', 'Sam Darnold', 'Derek Carr', 'Jimmy Garoppolo', 'Ryan Fitzpatrick', 'Daniel Jones', 'Drew Lock', 'Gardner MINSHEW', 'Dwayne Haskins', 'Baker Mayfield', 'Jameis Winston', 'Jarrett Stidham', 'Justin Herbert', 'Mitch Trubisky', 'Nick Foles', 'Andy Dalton', 'Mason Rudolph', 'David Blough', 'Devlin Hodges', 'Will Grier'];
  var qbTeams = ['KC', 'BAL', 'SEA', 'HOU', 'NO', 'GB', 'TEN', 'ARI', 'PHI', 'ATL', 'DAL', 'IND', 'TB', 'PIT', 'BUF', 'DET', 'MIN', 'FA', 'LAR', 'NYJ', 'LV', 'SF', 'MIA', 'NYG', 'DEN', 'JAC', 'WAS', 'CLE', 'NO', 'NE', 'LAC', 'CHI', 'CHI', 'DAL', 'PIT', 'DET', 'PIT', 'CAR']
  var qbOveralls = ['99', '97', '98', '95', '95', '92', '92', '90', '88', '86', '86', '86', '86', '86', '85', '84', '84', '83', '82', '82', '82', '82', '81', '80', '80', '80', '80', '79', '79', '79', '78', '77', '76', '76', '74', '73', '73', '72']
  var qb1 = Math.floor(Math.random() * Math.floor(37));
  var qbName1 = qbNames[qb1];
  var qbTeam1 = qbTeams[qb1];
  var qbOverall1 = qbOveralls[qb1];
  document.getElementById("qbDisplay1").innerHTML = qbName1 + '\xa0' + qbTeam1 + '\xa0' + qbOverall1;
  qbNames.splice(qb1, 1);
  var qb2 = Math.floor(Math.random() * Math.floor(36));
  var qbName2 = qbNames[qb2];
  var qbTeam2 = qbTeams[qb2];
  var qbOverall2 = qbOveralls[qb2];
  document.getElementById("qbDisplay2").innerHTML = qbName2 + '\xa0' + qbTeam2 + '\xa0' + qbOverall2;
  qbNames.splice(qb2, 2);
  var qb3 = Math.floor(Math.random() * Math.floor(35));
  var qbName3 = qbNames[qb3];
  var qbTeam3 = qbTeams[qb3];
  var qbOverall3 = qbOveralls[qb3];
  document.getElementById("qbDisplay3").innerHTML = qbName3 + '\xa0' + qbTeam3 + '\xa0' + qbOverall3;

当我执行此代码时,同一索引的 Names、Teams 和Overalls 元素不匹配。我怎样才能使它们确实对应并且“qbDisplay”例如是“Patrick Mahomes KC 99”?

标签: javascripthtmlarraysmath

解决方案


您只是从其中一个数组中删除随机选择的索引。您也应该对其他两个这样做:

qbNames.splice(qb1, 1);
qbTeams.splice(qb1, 1); // <--- add this 
qbOveralls.splice(qb1, 1); // <--- add this

当然,第二个选择也是如此,第三个也是如此。

如果您将三个属性一起存储在对象中,这样您就只有一个对象数组,这将是更好的做法。像这样:

var stats = [
  {name: 'Patrick Mahomes', team: 'KC', overall: 99 },
  {name: 'Lamar Jackson', team: 'BAL', overall: 97 },
  // ...etc
];

我会做的另一件事是使用 shuffle 函数,它随机地对上述数组进行洗牌。一旦你有了它,你就可以选择前三个(或者你需要多少个)。

不要分配独特的id属性,如qbDisplay1, qbDisplay2, ... 等,而是使用class属性并为这些元素使用相同的值。

我没有看到\x0a(不间断空格)的好处,因为您的数据名称中有正常空格。如果您不希望事物环绕,请改用 CSS 样式 ( white-space: nowrap)。

这是一个小演示:

function shuffle(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

var stats = [
  {name: 'Patrick Mahomes', team: 'KC', overall: 99 },
  {name: 'Lamar Jackson', team: 'BAL', overall: 97 },
  {name: 'Russell Wilson', team: 'SEA', overall: 98 },
  {name: 'Deshaun Watson', team: 'HOU', overall: 95 },
  {name: 'Drew Brees', team: 'NO', overall: 95 },
  {name: 'Aaron Rodgers', team: 'GB', overall: 92 },
  {name: 'Ryan Tannehill', team: 'TEN', overall: 92 },
  {name: 'Kyler Murray', team: 'ARI', overall: 90 },
  {name: 'Carson Wentz', team: 'PHI', overall: 88 },
  {name: 'Matt Ryan', team: 'ATL', overall: 86 },
];

let shuffled = shuffle([...stats]); // take a copy before shuffling

for (let display of document.querySelectorAll(".qbdisplay")) {
    let {name, team, overall} = shuffled.pop();
    display.textContent = name + ' ' + team + ' ' + overall;
}
<div class="qbdisplay"></div>
<div class="qbdisplay"></div>
<div class="qbdisplay"></div>

转换工具

要将您当前的数据结构转换为上面建议的数据结构,您可以使用以下工具。将三个数组复制/粘贴到输入框中,在输出框中,您将获得格式化为目标结构的等效数组。不要担心复制/粘贴超出需要的内容(您可能会留下/留下var ... =部分)。它将引号转换为双引号,因此如果您在名称中有这些,您可能需要在之后恢复该更改:

let input = document.querySelector("textarea");
let output = document.querySelector("pre");

input.addEventListener("input", refresh);
refresh();

function refresh() {
    let jsons = input.value.replace(/'/g, '"').match(/\[.*?\]/g);
    let result = [];
    if (jsons.length === 3) {
        try {
            let [names, teams, overalls] = jsons.map(JSON.parse);
            for (let i = 0; i < names.length; i++) {
                result.push({
                    name: names[i],
                    team: teams[i],
                    overall: overalls[i]
                });
            }
        } catch(e) {
            output.textContent = e.message;
            return;
        }
    }
    output.textContent = JSON.stringify(result, null, 2);
}
textarea { width: 100% }
<textarea>
var qbNames = ['Patrick Mahomes', 'Lamar Jackson', 'Russell Wilson', 'Deshaun Watson', 'Drew Brees', 'Aaron Rodgers', 'Ryan Tannehill', 'Kyler Murray', 'Carson Wentz', 'Matt Ryan', 'Dak Prescott', 'Philip Rivers', 'Tom Brady', 'Ben Roethlisberger', 'Josh Allen', 'Matthew Stafford', 'Kirk Cousins', 'Cam Newton', 'Jared Goff', 'Sam Darnold', 'Derek Carr', 'Jimmy Garoppolo', 'Ryan Fitzpatrick', 'Daniel Jones', 'Drew Lock', 'Gardner MINSHEW', 'Dwayne Haskins', 'Baker Mayfield', 'Jameis Winston', 'Jarrett Stidham', 'Justin Herbert', 'Mitch Trubisky', 'Nick Foles', 'Andy Dalton', 'Mason Rudolph', 'David Blough', 'Devlin Hodges', 'Will Grier'];
  var qbTeams = ['KC', 'BAL', 'SEA', 'HOU', 'NO', 'GB', 'TEN', 'ARI', 'PHI', 'ATL', 'DAL', 'IND', 'TB', 'PIT', 'BUF', 'DET', 'MIN', 'FA', 'LAR', 'NYJ', 'LV', 'SF', 'MIA', 'NYG', 'DEN', 'JAC', 'WAS', 'CLE', 'NO', 'NE', 'LAC', 'CHI', 'CHI', 'DAL', 'PIT', 'DET', 'PIT', 'CAR']
  var qbOveralls = ['99', '97', '98', '95', '95', '92', '92', '90', '88', '86', '86', '86', '86', '86', '85', '84', '84', '83', '82', '82', '82', '82', '81', '80', '80', '80', '80', '79', '79', '79', '78', '77', '76', '76', '74', '73', '73', '72']
</textarea>
<pre></pre>

请注意,此脚本必须在内容加载后运行(如上面的代码片段所示)。要使其正常工作,请确保您的 HTML 页面<script>...</script>在关闭之前有块</body>。所有其他 HTML 元素都应该在块的开头之前<script>出现。


推荐阅读