【问题标题】:Find remaining indexes and storing them as values查找剩余索引并将它们存储为值
【发布时间】:2020-11-27 06:48:17
【问题描述】:

我正在制作一个小游戏。您必须在随机杯子下找到球。

首先,图像存储在 nodeList 中。然后根据nodeList的长度随机计算出中奖杯。

我的问题:在计算出 winsCup 的随机值后,我不知道如何从“图像”节点列表中找到其他两个索引。如何计算两个不是随机获胜杯值的值?

我的想法是签发某种支票,但我不确定要检查什么。我的目标是让剩下的两个杯子切换到另一个“.png”,露出空杯子。

window.onload = function() {
    getImages();
}

function getImages() {
    var images = document.getElementsByTagName('img');
    var winningCup = Math.floor(Math.random() * images.length);
 
    var empty1 = Math.floor(Math.random() * images.length);
    var empty2 = Math.floor(Math.random() * images.length);

    if(empty1 || empty2 === winningCup){


    }

    for(var i = 0; i < images.length; i++) {
        images[winningCup].onclick = winCup;
     
    }
    console.log(empty1);
    console.log(empty2)
    console.log(winningCup)
}

function winCup(eventObj){
    var cup = eventObj.target;
    var name = cup.id;
    name = name + 'ball.png';
    cup.src = name; 

    //adds photo of winning cup
}

function losingCups(eventObj){
    var cups = eventObj.target;
    var name = cups.id;
    name = name + 'up.png';
    cups.src = name

    //adds photo of losing cups


}

【问题讨论】:

  • 很抱歉刚刚添加了它。
  • 您希望对数组进行洗牌,而不是为每个杯子生成一个新的随机数。

标签: javascript image random indexing


【解决方案1】:

您只需要一个随机获胜的杯子。其他人都输了,不是随机的。

function getImages() {
    var images = document.getElementsByTagName("img");
    var winningCup = Math.floor(Math.random() * images.length);
    for (var i = 0; i < images.length; ++i)
        images[i].onclick = i == winningCup ? winCup : losingCups;
}

【讨论】:

  • 嗨 TimTim 它告诉我 forEach 不是一个函数。
  • 针对旧版浏览器更新
【解决方案2】:

使用中奖杯号过滤器删除。

function arrayRemove(arr, value) { 
return arr.filter(function(ele){ 
return ele != value; 
});}

var losingCups = arrayRemove(array, winningCup);

【讨论】:

  • 这个答案看起来不完整。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2016-03-31
  • 1970-01-01
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
相关资源
最近更新 更多