gpt4 book ai didi

javascript - 尝试迭代时,嵌套 JSON 数组抛出“未定义的 "Uncaught TypeError: Cannot read property ' 长度”

转载 作者:行者123 更新时间:2023-11-28 06:06:51 26 4
gpt4 key购买 nike

我试图找出为什么我的代码抛出此错误:未捕获的类型错误:无法读取未定义的属性“长度”。

此错误消息引用此行:“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++) {
...
}
}

关于javascript - 尝试迭代时,嵌套 JSON 数组抛出“未定义的 "Uncaught TypeError: Cannot read property ' 长度”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36774415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com