[英]Javascript: How to get the value of a function?
I am making a quick game where a player damages a enemy npc. 我正在制作一款快速游戏,玩家在游戏中会伤害敌方NPC。 I have a function below that does the calculation for the damage, but I can't get the console log to say i'm doing "X" amount of damage.
我下面有一个函数来计算损坏,但是我无法获得控制台日志来说明我正在造成“ X”倍的损坏。 What am I doing wrong?
我究竟做错了什么? Instead, it just pulls up the function statement, but I want it to give me the functions value!
取而代之的是,它只是拉出function语句,但是我希望它给我功能值!
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
I'm calling my function in another code properly, but when I try to console log the damage in that other code, I get a error. 我在另一个代码中正确调用了我的函数,但是当我尝试在另一个代码中控制台记录损坏时,我得到了一个错误。
function attackButton() {
darkwarrior.hp = darkwarrior.hp - damage();
console.log(darkwarrior.hp);
console.log(damage);
If you run console.log(damage());
如果您运行
console.log(damage());
you will get the "X" amount of damage instead of the function statement. 您将获得“ X”的损害赔偿额而不是功能声明。 So you could change
attackButton()
function to be: 因此,您可以将
attackButton()
函数更改为:
function attackButton() {
var damageDealt = damage();
darkwarrior.hp = darkwarrior.hp - damageDealt;
console.log(darkwarrior.hp);
console.log(damageDealt);
I'm not sure to understand, you want to log the result? 我不确定是否要记录结果? If so, you can do that:
如果是这样,您可以这样做:
var damage = function() {
return Math.floor(Math.random() * 5 + 1);
};
console.log(damage());
EDIT: 编辑:
you forgot the (). 您忘记了()。 + the value will not be the same if you don't put it in a variable:
+如果不将其放在变量中,则该值将不同:
function attackButton() {
var amount = damage()
darkwarrior.hp = darkwarrior.hp - amount;
console.log(darkwarrior.hp);
console.log(amount);
}
you just have to use an expression to assign the value to a variable. 您只需要使用表达式即可将值分配给变量。 Then log it.
然后登录。 Then return it.
然后返回。
var damage = function() { var num = Math.floor(Math.random() * 5 + 1); console.log(num); return num; }; damage();
Something like this should work for you. 这样的事情应该为您工作。
function NPC(startingLife, name) { this.hp = startingLife; this.name = name } NPC.prototype.takeDamage = function(amount) { this.hp = Math.max(this.hp - amount, 0); if (this.hp == 0) { console.log(this.name + " Dies"); } return this.hp; }; function damage() { return Math.floor(Math.random() * 5 + 1); } var darkwarrior = new NPC(4, 'Dark Warrior'); function attackButton() { var amount = damage(); darkwarrior.takeDamage(amount); console.log("Dark Warrior took " + amount + " points of damage"); } document.querySelector('#attack-button').addEventListener("click", attackButton);
<button id="attack-button">ATTACK!</button>
You are just returning the value instead of printing it. 您只是返回值而不是打印它。 You should instead replace return with console.log(
您应该改为用console.log(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.