我试图弄清楚为什么我的代码引发此错误:Uncaught TypeError:无法读取未定义的属性“ length”。

此错误消息引用以下行:“ for(var j = 0; j
我不知道为什么会发生此错误,我已经使用JSONLint检查了我的JSON代码,并说没有错误。任何帮助和建议,将不胜感激!

var pluginsJson = {
    "installedPlugins": [
        {
            "pluginName": "Chrome PDF Viewer",
            "pluginVersion": "",
            "pluginDescription": "Portable Document Format",
            "pluginFilename": "internal-pdf-viewer",
            "installedMimes": [
                {
                    "mimeType": "application/x-google-chrome-pdf",
                    "mimeDesc": "Portable Document Format",
                    "mimeSuffixes": "pdf"
                },
                {
                    "mimeType": "application/x-nacl",
                    "mimeDesc": "Native Client Executable",
                    "mimeSuffixes": ""
                }
            ]
        },
        {
            "pluginName": "Widevine Content Decryption Module",
            "pluginVersion": "",
            "pluginDescription": "Enables Widevine licenses for playback of HTML audio/video content. (version: 1.4.8.866)",
            "pluginFilename": "widevinecdmadapter.dll"
        },
        {
            "pluginName": "Shockwave Flash",
            "pluginVersion": "",
            "pluginDescription": "Shockwave Flash 21.0 r0",
            "pluginFilename": "pepflashplayer.dll"
        },
        {
            "pluginName": "Native Client",
            "pluginVersion": "",
            "pluginDescription": "",
            "pluginFilename": "internal-nacl-plugin"
        }
    ]
};

var pluginString = "";
var pluginObj;
var mimeObj;

for (var i = 0; i < pluginsJson.installedPlugins.length; i++) {
    pluginObj = pluginsJson.installedPlugins[i];

    pluginString += pluginObj.pluginName;
    pluginString += " | ";
    pluginString += pluginObj.pluginFilename;
    pluginString += " | ";
    pluginString += pluginObj.pluginDescription;
    pluginString += " | ";
    pluginString += pluginObj.pluginVersion;
    pluginString += "<br>";

    for (var j = 0; j < pluginObj.installedMimes.length; j++) {
        mimeObj = pluginObj.installedMimes[j];

        pluginString += mimeObj.mimeType;
        pluginString += " /\ ";
        pluginString += mimeObj.mimeDesc;
        pluginString += " /\ ";
        pluginString += mimeObj.mimeSuffixes;
        pluginString += "<br>";
    }
    pluginString += "<br>";
}

最佳答案

之所以会出现该错误,是因为并非所有pluginObj都定义了installedMimes

您可以通过两种方式解决此问题:

a)将"installedMimes": []添加到json中存在的所有插件。

b)更新您的JS代码以检查installedMimes是否存在。

if (pluginObj.installedMimes) {
    for (var j = 0; j < pluginObj.installedMimes.length; j++) {
        ...
    }
}

10-08 13:01