JavaScript:使用函数参数检索 JavaScript 对象键

JavaScript: Using a function parameter to retrieve a javascript object key

本文关键字:JavaScript 检索 对象 参数 函数      更新时间:2023-09-26

这是'未定义'的原因吗,有没有办法避免它?

我正在尝试从我的错误消息对象中动态检索所需的错误消息。这是一个非常简化的版本。

var language = {
    errorMsg: {
        helloWorld: "hello world"
    }
};
function displayErrorMsg(msg) {
    console.log(msg); // output: helloWorld
    console.log(language.errorMsg.helloWorld); // output: hello world
    console.log(language.errorMsg[msg]); // output: Uncaught ReferenceError: helloWorld is not defined 
}
displayErrorMsg('helloWorld');

在你的例子中language.errorMsgTSD不存在

你可以做:

function displayErrorMsg(msg) {
    console.log(language.errorMsg[msg]); // output: hello world
}

errorMsgTSD 未在任何地方定义。

它是未定义的,因为language没有errorMsgTSD字段。您需要像这样创建它:

var language = {
    errorMsg: {
        helloWorld: "hello world"
    },
    errorMsgTSD: {
        helloWorld: "hello world"
    },
};

或者,也许您需要将函数更改为:

function displayErrorMsg(msg) {
    console.log(msg);
    console.log(language.errorMsg[msg]);
}