2013-12-23 37 views
-1

僅嘗試將h1.name打印到控制檯,但我收到ReferenceError: h1 is not defined錯誤。如果我輸入1,2或3,則無關緊要,仍然是同樣的錯誤。我究竟做錯了什麼?簡單變量未在Javascript中定義參考錯誤

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

'h1' varibale只存在於'start()'函數內部,它是本地的。 –

+0

無論如何,這並不是理想的var聲明。你應該在函數的開頭聲明你的變量。 JavaScript變量只是函數範圍的,因此在'if-else'塊中聲明變量是沒有意義的 – jasonscript

+0

只返回你想要訪問的內容:return {h1:h1,h2:h2}和引用是這樣的:start() .h1.name;你可以在你的啓動函數中的最後一個「}」之前做返回。 –

回答

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. 這不是蟒蛇,從而預期

    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階梯。

+0

這並不能解決問題。 'h1'變量在'start'函數中被聲明,這意味着當OP嘗試打印'h1'時,它超出了範圍 – jasonscript

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) 
+0

yes,也被稱爲關聯數組。 –