首页 文章

在事件中设置数组中的布尔值

提问于
浏览
0

我有一个在点击事件中触发的功能 .

基本上,我有两个元素,它们是一个名为 chosenChar 的数组中的对象 . 这两个对象都以名为 isAttacker 的布尔属性开头为false .

单击"attack"按钮时,想法是随机选择数组中的一个对象,并将其 isAttacker 布尔值更改为true . 此外,我们深入攻击该攻击者对象,从对象内的阵列中获取攻击,获取攻击值,然后将其打印到屏幕上 .

我的目标是,如果我将攻击者布尔值设置为true,则原始数组中的剩余元素必须设置为false(因为它最初),我需要计算对防御对象(字符)造成的损害 .

现在一切都是控制台记录“真实”,它不会进入if语句,以确定是否有一名后卫并根据攻击计算角色的 Health 状况 .

var attackChar = [];
var defendingChar = [];

// get a random character to attack
attackChar = chosenChar[Math.floor(Math.random()*chosenChar.length)];
var attackCharName = attackChar.name;
attackChar.isAttacker = true;
console.log("the attacker is " + attackChar.name + " and isAttacker is " + attackChar.isAttacker);

for (var i = 0; i < chosenChar.length; i++) {
    if(chosenChar[i].isAttacker === true) {
       console.log(chosenChar[i].name + " is the attacker");
    } else {
       console.log(chosenChar[i].name + " is not the attacker");
    }
}

enter image description here

1 回答

  • 0

    一旦选择了 attackChar ,就可以遍历所有字符并将 isAttacker 标志设置为false,除了新的攻击者之外 .

    attackChar = chosenChar[Math.floor(Math.random()*chosenChar.length)];
    var attackCharName = attackChar.name;
    
    // set isAttacker to true/false based on the attackChar
    chosenChar.forEach(function(char) {
        char.isAttacker = char === attackChar;
    });
    
    for (var i = 0; i < chosenChar.length; i++) {
        if(chosenChar[i].isAttacker === true) {
           console.log(chosenChar[i].name + " is the attacker");
        } else {
           console.log(chosenChar[i].name + " is not the attacker");
        }
    }
    

    另一种方法是使用单独的值来保存攻击者,而不是更新每个字符的 isAttacker 值 .

    你实际上已经完成了这个( chosenChar ),所以 isAttacker 值在技术上并不是必需的,但你可能会发现它比依赖浮动的单独变量更方便 .

    attackChar = chosenChar[Math.floor(Math.random()*chosenChar.length)];
    for (var i = 0; i < chosenChar.length; i++) {
        if(chosenChar[i] === attachChar) {
           console.log(chosenChar[i].name + " is the attacker");
        } else {
           console.log(chosenChar[i].name + " is not the attacker");
        }
    }
    

相关问题