這是我的第一篇文章。我正在用 Javascript 練習函式和工廠函式。我創建了兩個怪物和一個讓它們互相攻擊并調整生命值的功能。當攻擊函式運行并將陳述句記錄到控制臺時,怪物新生命值的值回傳為 NaN。我已經用 typeof 進行了測驗,以確保健康和攻擊都是數字,但無法讓新的健康數字出現。
function monsterFactory(type,health,skinColor,strength,weakness,sound){
return{
type,
health,
skinColor,
strength,
weakness,
actions: {
attack(){
const randomAttak = Math.floor(Math.random()*3) 1;
switch(randomAttak){
case 1:
return 1;
break;
case 2:
return 2;
break;
case 3:
return 3;
break;
}
},
scream(){
const randomScream = Math.floor(Math.random()*3) 1;
switch(randomScream){
case 1:
console.log(`Moan`);
break;
case 2:
console.log(`Grumble`);
break;
case 3:
console.log(`Snarl`);
break;
}
},
}
}
}
const zombie = monsterFactory('Zombie',5,'Grey','Feels no pain','Slow','moan')
console.log(zombie.health)
const vampire = monsterFactory('Vampire',5,'White','Immortal','Sunlight','Hiss')
console.log(vampire.actions.attack()>zombie.actions.attack())
function attack(enemyOne,enemyTwo){
if(enemyOne.actions.attack() > enemyTwo.actions.attack()){
enemyTwo.health = enemyTwo.health - enemyOne.actions.attack
console.log(`${enemyTwo.type} has been struck their health is now ${enemyTwo.health}`)
}else if(enemyTwo.actions.attack()>enemyOne.actions.attack()){
enemyOne.health = enemyOne.health - enemyOne.actions.attack
console.log(`${enemyOne.type} has been struck their health is now ${enemyOne.health}`)
}
}
attack(zombie,vampire)
uj5u.com熱心網友回復:
在您的攻擊功能中,您使用enemyOne.actions.attack
. 但是,這只是對函式本身的參考,并不運行函式,因此是 NaN 值。要修復它,只需確保運行該功能。
固定attack()
功能:
function attack(enemyOne,enemyTwo){
if(enemyOne.actions.attack() > enemyTwo.actions.attack()){
enemyTwo.health = enemyTwo.health - enemyOne.actions.attack()
console.log(`${enemyTwo.type} has been struck their health is now ${enemyTwo.health}`)
}else if(enemyTwo.actions.attack()>enemyOne.actions.attack()){
enemyOne.health = enemyOne.health - enemyOne.actions.attack()
console.log(`${enemyOne.type} has been struck their health is now ${enemyOne.health}`)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/506856.html
標籤:javascript 功能 楠