var currDice, totDice, dice, complete;
function moveIt(){
dice = Math.floor(Math.random()*6) + 1,
currDice = 40,
totDice = totDice+complete,
complete = dice * currDice
return totDice;
};
函数moveIt
返回NaN
。
它应该随机返回 40 到 6 的倍数并保持之前的值。
如果我删除它返回Undefined
.
我知道这是一个范围问题。请帮忙。
您complete
在初始化之前正在使用它!你必须交换你的代码行:
function moveIt(beforeTotal) {
var dice = Math.floor(Math.random()*6) + 1;
var currDice = 40;
var complete = dice * currDice;
var totDice = (beforeTotal || 0)+complete;
return totDice;
};
var total = moveIt();
console.log(total);
total = moveIt(total);
console.log(total);
我试图指出这种方法是如何工作的。
您可以在没有初始值的情况下调用此函数。然后(beforeTotal || 0)
is(undefined || 0)
并且 will 求值为0
,这是 JS 逻辑,你得到一个骰子的结果。
如果你向这个函数传递一个值,它将被用来添加complete
到它。通过传递 1000 并完成获得 120,您将获得 1120。
所有其他变量仅在此函数中可用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句