【问题标题】:Javascript: Trying to randomly move items from one array to anotherJavascript:尝试将项目从一个数组随机移动到另一个数组
【发布时间】:2017-08-30 16:49:18
【问题描述】:

我已经被困了几个小时,现在试图从一个数组(玩家)随机选择一个项目到另一个(team1)。

我已经通过使用 splice 做其他事情来让它工作,但不幸的是,splice 使用已删除的项目创建了一个数组,所以我最终得到了一个带有数组的数组。

这是我目前得到的:

var players = ["P1", "P2", "P3", "P4"];

var team1 = [];
var team2 = [];

var select = Math.floor(Math.random() * players.length);
var tmp;

if (team1.length < 2) {
  tmp.push(players.splice(select, 1));
  team1.push(tmp.pop);
}

console.log(team1);
console.log(tmp);
console.log(players);

如果我做错了,对不起,对这个网站还是很陌生,感谢帮助。

【问题讨论】:

标签: javascript arrays splice


【解决方案1】:

你只需要在拼接并推送到团队时从数组中选择第一个元素,

var players = ["P1", "P2", "P3", "P4", "P5", "P6", "P7", "P8"];

var team1 = [];
var team2 = [];

var tmp = [];
while (team1.length < 4) {
  tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
  team1.push(tmp.pop());
}

while (team2.length < 4) {
  tmp.push(players.splice(Math.floor(Math.random() * players.length - 1), 1)[0]);
  team2.push(tmp.pop());
}

console.log(team1);
console.log(team2);
console.log(tmp);
console.log(players);

【讨论】:

  • 感谢您的帮助,请问这是为什么呢?我什至不知道您可以像这样在推送和拼接结束时选择索引
  • 如果函数返回数组中的值,如结构(数组或节点列表),无论结果如何,我们都可以通过索引访问其中的值。
  • 对不起,还有一个问题,我把它改成了一个while循环,这样我就可以把它们分成两个团队,它只在一部分时间工作,其他时候它将 undefined 放入团队数组中, 你知道为什么吗?这是链接:codepen.io/Buckets/pen/wqQxzP?editors=1111
  • 您必须为 while 循环中的每个项目创建不同的随机选择,因为您使用相同的选择,在某些时候选择值会变得大于数组大小,因为我们是从父数组中切片的。我已经更新了我的答案看看
【解决方案2】:

你在你的场景中尝试这样

var players = ["P1", "P2", "P3", "P4"];

var team1 = [];
var team2 = [];
var temp = players.slice();

for(i=0; i<temp.length; i++){
     var select = Math.floor(Math.random() * temp.length);
     console.log(select);
     if (team1.length <= temp.length/2) {
        team1.push(temp[select]);
      }
      temp.splice(select, 1);
}
team2 = temp.slice();

console.log('team 1 ---',team1);
console.log('team 2 ---',team2);
console.log('players ---', players);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2018-10-04
    • 1970-01-01
    • 2018-02-05
    相关资源
    最近更新 更多