我试图弄清楚为什么我的代码会抛出此错误:未捕获TypeError:无法读取属性' length'未定义的。
此错误消息引用此行:" for(var j = 0; j< pluginObj.installedMimes.length; 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>";
}
答案 0 :(得分:0)
您收到该错误,因为并非所有pluginObj
定义installedMimes
。
您可以通过两种方式解决此问题:
a)将"installedMimes": []
添加到json中的所有插件。
b)更新您的JS代码以检查是否存在installedMimes
。
if (pluginObj.installedMimes) {
for (var j = 0; j < pluginObj.installedMimes.length; j++) {
...
}
}
答案 1 :(得分:0)
我发现只有第一个installedMimes
中有installedPlugin
个数组,而其他数据中没有...
我会在你的内循环之前添加一个测试:
if (typeof pluginObj.installedMimes !== 'undefined') {
for (var j = 0; j < pluginObj.installedMimes.length; j++) {
...
}
}