-1

只是试图打印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)
4

2 回答 2

3

您应该在函数外部声明h1start以便函数外部的代码可以看到它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 阶梯中包含一个条件总是好的。

于 2013-12-23T03:42:37.183 回答
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)
于 2013-12-23T03:54:41.477 回答