开发者

Help with adding variable to self and random number (javascript)

开发者 https://www.devze.com 2023-03-04 12:10 出处:网络
I am making a simple dice roller, which seems like a good first project to me, and may help others learn javascript as well, and when you roll a die (with a button), it is supposed to add to the total

I am making a simple dice roller, which seems like a good first project to me, and may help others learn javascript as well, and when you roll a die (with a button), it is supposed to add to the total (there is a clear button), but it says NaN. Here is my code:

<html>
<body>
<script type="text/javascript">
function load()
{
document.getElementById("press").value=" "
var x=0
}
function d6()
{
var x=x+(Math.floor((Math.random() * 6) + 1));
document.getElementById("press").value=(x)
}
load()
</script>
<input type="button" value="Roll d6" onclick="d6()"/>
<input type="text" id="press"/>
</b>
<input type="button" value="Clear" onclick="load()"/>
</body&开发者_运维百科gt;
</html>

Help would be greatly appriciated. Thanks!


This is happenning because variable x is not initialised when you are using it in d6(). The scope of the 2 functions is different.

You need x to be a global variable. For that, use the following code structure:

x = 0
function load() { ... }
function d6() { ... } 

Remember that when you declare a variable with the keyword 'var' preceding it, the variable is considered local. A variable without a 'var' is considered global.


Your x variables are local to the functions. change x to be a global variable:

var x;
function load() { ... }
function d6() { ... }


When using JavaScript it is important to consider the scope of names and values. Consider the difference between this:

var x = 2;
function assignX(v) {
    x = v;
}
print(x); // 2 
assignX(3);
print(x); // 3

and this:

function assignX(v) {
    var x = v;
}
print(x); // undefined
assignX(3);
print(x); // undefined

In the first example x exists in the global scope which encloses all names and values. In the second example x only exists within the function assignX.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号