繁体   English   中英

如何过滤到数组并从中选择一个随机 ID?

[英]How can I filter to an array and choose a random Id from it?

各位晚安。

我是编程新手,不到 2 个月,所以我不太明白如何进行这项工作。 这正是我想要做的:我正在尝试制作这个游戏,它需要在符合条件“活着”和“能够使用奖品”的现有单位之间进行抽奖。 为此,有人告诉我,我需要为可以接收它的单元包含一个带有单元 ID 的数组,然后通过“活着”过滤它们以供随机生成器选择。 问题是,我不知道如何使这项工作。 我试过这段代码,但它不起作用。 任何人都知道为什么或如何我应该这样做?

var rafflearray = []; // the array containing the units
if (root.getExternalData().isUnitRegistered() = true) {var character = root.getCurrentSession().getPlayerList().getData()}; // establish the character as a variable

if (var character.getAliveStatus = true ) {rafflearray.push(character)}; // checks his alive status and send him to the array

var chosen = rafflearray [Math.random()*chosenarray.lenght]; // to choose amongst them
chosen.addItem()

提前感谢您的关注!

我强烈建议在此项目之前阅读 Javascript 基础知识(此处为第 1 和第 2 部分)。 但是我希望这个答案可以帮助你

首先,您不能在if语句中使用var ,例如

 if(var character.getAliveStatus = true) 

您需要使用=====而不是= ,例如:

if(isAlive === true){
    // Code to be executed
}
// the difference between '==' and '===' can be found in the docs mentioned below

请参阅第 3 节的此处Javascript 运算符

var用于声明不限于其父块的变量, 请参阅 javascript 范围

在您的情况下,我不确定您是否已经拥有一系列玩家,或者您是否正在尝试制作一个。

在第一种情况下,我建议你使用Array.filter() function 这是一个很酷的方法。 例如:

// Assuming 'players' is the array of players in the game

// filtering out raffle worthy players
let raffle_worthy = players.filter(player => player.getAliveStatus === true); 

// Randomly choosing 1 person between the raffle worthy players
let chosen = raffle_worthy[Math.floor(Math.random * raffle_worthy.length)]

您可能想查看Array.filter()文档,并且在上面的示例中还使用了Js Math

另一方面,如果您没有大量玩家并一个一个地获得他们,我不确定我是否能理解您获得用户的方式以及聚集他们的方式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM