【问题标题】:Splitting variable with json leads to Uncaught TypeError用 json 拆分变量会导致 Uncaught TypeError
【发布时间】: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


【解决方案1】:

您在假设始终定义 json 变量的情况下运行您的切换案例,但如果运行了 catch() 块,则意味着您的 json 变量将未定义:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // an error got caught, this block runs regardless, and now json is undefined
        console.log(`json variable: ${json}`);
    }
}

const result = example(";");
console.log(result);

您还假设如果您在 catch() 块中有一个 return 语句,这将阻止 finally 块执行,但事实并非如此。 finally 块将执行其代码,然后才会返回一些语句。

另请注意,如果您在 catchfinally 块中都有 return 语句,则 finally return 语句将优先于另一个:

function example(value) {
    var json;

    try {
        json = JSON.parse(value);
    } catch (err) {
        // couldn't parse the value, so you catch an error
        console.error(err);

        return "catch";
    } finally {
        // but this return statement takes priority over catch
        return "finally";
    }
}

const result = example(";");
console.log(result);

【讨论】:

    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-04
    • 2018-12-09
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    相关资源
    最近更新 更多