只是尝试将h1.name
打印到控制台,但我收到ReferenceError: h1 is not defined
错误。如果输入1,2或3,仍然是相同的错误并不重要。我做错了什么?
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)
答案 0 :(得分:3)
您应该在h1
函数之外声明start
,以便start
函数之外的代码可以看到它。
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);
...
备注:强>
这不是python,因此这种情况可能无法正常工作
if (0 < nHands < 4 ) {
你需要的是
if (nHands < 4 && nHands > 0) {
您要声明nHands
两次,这不是必需的,您可以将输入数据转换为这样的数字
var nHands=parseInt(prompt("How many hands do you want to play?(1,2 or 3)"));
将else
条件包含在if-else阶梯中总是好的。
答案 1 :(得分:1)
你也可以把手中的对象填充到哈希中,就像这样。 警告:这只是让您的“h1,h2,h3”可以像您期望的那样访问。海报“thefourtheye”给出了一个强烈/清晰的想法,可能你想去哪里。
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)