【发布时间】:2020-09-16 19:09:53
【问题描述】:
我正在尝试拆分变量pickerValue 的内容,以便最终结果只显示“eosptest2”
console.log 显示pickerValue: i:0#.w|opmain\eosptest2;
问题是我在以下行得到Uncaught TypeError: Cannot read property '0' of undefined:
return json[0].id.split("\\")[1];
这是函数:
function getUserNameFromPeoplePicker(pickerValue, returnType) {
if (checkNull(pickerValue) == "") {
return "";
}
var json;
try {
json = JSON.parse(pickerValue);
} catch (err) {
return replaceSubstring(pickerValue.split("\\")[1], ";", "");
} finally {
switch (returnType) {
case "label":
console.log("json[0].label: " + json[0].label);
return json[0].label;
break;
case "id":
console.log("pickerValue: " + pickerValue);
// console.log("Json id split: " + json[0].id.split("\\")[1]);
return json[0].id.split("\\")[1];
default:
return replaceSubstring(pickerValue.split("\\")[1], ";", "");
//return replaceSubstring(json[0].value.split("\\")[1], ";", "");
break;
}
}
}
为了测试它,我用return "eosptest2" 替换了return 语句,它运行良好,但我不知道究竟需要更改什么。
如何解决这个问题?
【问题讨论】:
-
您能否记录并在问题中包含
pickerValue中的值?因为您的变量json似乎是未定义的。 -
@GhassenLouhaichi 抱歉,我应该创建一个 console.log() 的什么?
-
当您收到关于
json未定义的控制台错误时,我想看看pickerValue里面有什么。 -
console.log(json);说undefined -
您为什么不在
catch()中记录错误?我认为这就是它出错的地方。问题是当catch()运行时,这意味着json将保持未定义,并且finally块中的两个switch case 将始终抛出错误。
标签: javascript json split typeerror