2013-05-01 57 views
0

因此,這裏是我的代碼:的console.log顯示對象,但打電話時遞歸函數獲取錯誤

function makeContent(jsonData){ 
    var aProperty, containerType, contentContainerName, containerIdentifier, containerComment, theContent ; 

    for(aProperty in jsonData){ 
     switch(aProperty){ 
      case "containerType": containerType = jsonData[aProperty]; 
      case "contentContainerName" : contentContainerName = jsonData[aProperty]; 
      case "containerComment" : containerComment = jsonData[aProperty]; 
      case "containerIdentifier" : containerIdentifier = jsonData[aProperty]; 
      case "itemContent" : theContent = jsonData[aProperty]; 
     } 
    } 


    if(theContent.hasOwnProperty){ 
     console.log(theContent); 
     makeContent(theContent); 
    } 

我得到這個作爲我的輸出:

[Object] footer.js:59

TypeError: 'undefined' is not an object (evaluating 'theContent.hasOwnProperty') footer.js:58

這只是沒有任何意義我因爲當我console.log(TheContent)我得到一個對象,它工作正常。該錯誤只發生在我嘗試遞歸調用該函數時添加makeContent函數。所以我沒有添加return語句,因爲這個錯誤,我應該這樣做嗎?

+1

你錯過了一個關閉'}'的地方,可能是結束。 (只是一個語法的東西,與你的問題無關) – 2013-05-01 02:04:02

+0

'theContent'並不總是被定義的, – Blender 2013-05-01 02:07:13

+1

另外,[loop-switch sequence](http://en.wikipedia.org/wiki/Loop-switch_sequence):( – Phil 2013-05-01 02:07:56

回答

1

您似乎在使用條件表達式if(theContent.hasOwnProperty)來確定是否定義了theContent。該變量在函數頂部聲明,並且僅在最終的case中定義。

檢查,如果一個變量定義的最可靠的辦法是,像這樣:

if (typeof theContent !== 'undefined`) { ... } 

當不執行最終case聲明,theContent沒有定義,並且試圖在一個不確定的值會導致訪問hasOwnProperty觀察到的錯誤。

+0

啊,謝謝,解決了它,我認爲Javascript一行一行,並認爲內容將在它到達函數調用之前被定義。 – pmac89 2013-05-01 02:20:26