Just trying to print h1.name
to console, but I'm receiving a ReferenceError: h1 is not defined
error. It doesn't matter if I type 1, 2, or 3, still the same error. What am I doing wrong?
function Hand(name, sChips) {
this.name = name;
this.sChips = sChips;
}
function start() {
var nHands = prompt("How many hands do you want to play?(1,2, or 3)");
var nHands = Number(nHands);
if (0 < nHands < 4 ) {
if (nHands === 1) {
var h1 = new Hand("First Hand", 150000);
}
else if (nHands === 2) {
var h1 = new Hand("First Hand", 75000);
var h2 = new Hand("Second Hand", 75000);
}
else if (nHands === 3) {
var h1 = new Hand("First Hand", 50000);
var h2 = new Hand("Second Hand", 50000);
var h3 = new Hand("Third Hand", 50000);
}
else {
start();
}
}
};
start();
console.log(h1.name)
You should declare h1
outside the start
function, so that it will visible to the code outside the start
function.
var h1, h2, h3;
function start() {
var nHands=parseInt(prompt("How many hands do you want to play?(1,2 or 3)"));
...
if (nHands === 1) {
h1 = new Hand("First Hand", 150000);
...
Notes:
This is not python, so this condition might not work as intended
if (0 < nHands < 4 ) {
what you need is
if (nHands < 4 && nHands > 0) {
You are declaring nHands
twice, which is not necessary, you can convert the input data to the number like this
var nHands=parseInt(prompt("How many hands do you want to play?(1,2 or 3)"));
It is always good to include an else
condition, to your if-else ladder.
you could also just stuff the hand objects in a hash, like so. Caveat: this just enables your "h1,h2,h3" to be accessible like you expect. poster "thefourtheye" has given a robust/clear idea of probably where you want to go.
function Hand(name, sChips) {
this.name = name;
this.sChips = sChips;
}
var h = {}; //global h obj
function start() {
var nHands = prompt("How many hands do you want to play?(1,2, or 3)");
var nHands = Number(nHands);
if (0 < nHands < 4 ) {
if (nHands === 1) {
h.h1 = new Hand("First Hand", 150000);
}
else if (nHands === 2) {
h.h1 = new Hand("First Hand", 75000);
h.h2 = new Hand("Second Hand", 75000);
}
else if (nHands === 3) {
h.h1 = new Hand("First Hand", 50000);
h.h2 = new Hand("Second Hand", 50000);
h.h3 = new Hand("Third Hand", 50000);
}
else {
start();
}
}
};
start();
console.log(h.h2.name, h['h2'].name)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.