Console.log显示对象,但递归调用函数时得到错误

console.log shows object but when recursively calling function gets error

本文关键字:函数 错误 调用 递归 显示 log 对象 Console      更新时间:2023-09-26

下面是我的代码:

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: 'undefined'不是一个对象(求值'theContent.hasOwnProperty') footer.js:58

这对我来说没有意义,因为当我console.log(内容)我得到一个对象,它工作得很好。只有在尝试递归调用makeContent函数时添加该函数时才会出现错误。由于这个错误,我没有添加返回语句,我应该这样做吗?

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

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

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

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