JavaScript:使用函数参数检索javascript对象键
16lz
2021-01-22
Is there a reason this is 'undefined, and is there a way to avoid it?
有没有理由这是'未定义的,有没有办法避免它?
I am trying to dynamically retrieve the desired error message from my error messages object. This is a very simplified version of it.
我试图从我的错误消息对象动态检索所需的错误消息。这是它的一个非常简化的版本。
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');
3 个解决方案
#1
2
Well in your example language.errorMsgTSD
does not exist
那么在您的示例language.errorMsgTSD不存在
You could do:
你可以这样做:
function displayErrorMsg(msg) {
console.log(language.errorMsg[msg]); // output: hello world
}
更多相关文章
- 键盘出现时,UIWebView滚动。导致点击偏移错误?
- 如何使用try,catch在错误处理中打印消息
- 关于洗牌算法的错误认识
- CORS错误:请求标头字段预检响应中的Access-Control-Allow-Headers
- JSON.parse(xhr.responseText)意外的字符串错误
- 当尝试安装节点时,会得到一个“DLL”错误。js在Windows 7上
- VBA中的错误处理
- 错误地将JSON数据写入文件。
- jquery ajax readystate 0 responsetext status 0 stext错误