简单变量未在Javascript中定义引用错误

时间:2013-12-23 03:39:00

标签: javascript referenceerror

只是尝试将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)

2 个答案:

答案 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);
    ...

备注:

  1. 这不是python,因此这种情况可能无法正常工作

    if (0 < nHands < 4 ) {
    

    你需要的是

    if (nHands < 4 && nHands > 0) {
    
  2. 您要声明nHands两次,这不是必需的,您可以将输入数据转换为这样的数字

    var nHands=parseInt(prompt("How many hands do you want to play?(1,2 or 3)"));
    
  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)