0

所以这是我的代码:

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);
    }

我得到这个作为我的输出:

[对象] footer.js:59

TypeError:“未定义”不是对象(评估“theContent.hasOwnProperty”)footer.js:58

这对我来说没有意义,因为当我 console.log(theContent) 我在其中得到一个对象并且它工作正常。该错误仅在我尝试递归调用该函数时添加 makeContent 函数时发生。所以由于这个错误我没有添加return语句,我应该这样做吗?

4

1 回答 1

1

您似乎正在使用条件表达式if(theContent.hasOwnProperty)来确定是否theContent已定义。该变量在函数顶部声明,并且仅在 final 中定义case

检查变量是否已定义的最可靠方法如下:

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

当最终case语句未执行时,theContent未定义并尝试访问hasOwnProperty未定义的值将导致观察到的错误。

于 2013-05-01T02:08:21.303 回答