【问题标题】:How can I filter to an array and choose a random Id from it?如何过滤到数组并从中选择一个随机 ID?
【发布时间】:2022-01-10 06:00:35
【问题描述】:

晚安,伙计们。

我是编程新手,不到 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()

提前感谢您的关注!

【问题讨论】:

  • Math.floor(Math.random() * selectedArray.length) - 试试这个

标签: javascript arrays filter


【解决方案1】:

我强烈建议在此项目之前阅读 Javascript 基础知识 (here section 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 节中here 中的 Javascript 运算符

var 用于声明一个不限于其父块的变量see javascript scoping

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

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

// 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

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

【讨论】:

    猜你喜欢
    • 2016-01-18
    • 2021-10-18
    • 2020-12-17
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2012-02-21
    • 1970-01-01
    • 2018-03-24
    相关资源
    最近更新 更多