javascript 如何访问包含特殊字符的对象属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12953704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:30:28  来源:igfitidea点击:

How to access object properties containing special characters?

javascript

提问by user1673257

I have a formDOM element:

我有一个formDOM 元素:

var virDom = document.getElementsByTagName("form")[0];

virDomhas two fields with IDs creditIdand pwdId... I can access virDom.creditIdwithout any issue but, virDom.pwdId..is failing with a syntax error, because of the periods contained in the name.

virDom有两个带有 IDcreditId和 的字段pwdId..。我可以virDom.creditId毫无问题地访问,但是virDom.pwdId..由于名称中包含句点而失败并出现语法错误。

How can I access such properties?

我如何访问这些属性?

回答by Niet the Dark Absol

Use bracket notation:

使用括号表示法

virDom['creditId']
virDom['pwdId..']

This applies to any object, and it is particularly useful for non-identifier-safe characters and also for accessing keys that you may not know ahead of time.

这适用于任何对象,对于非标识符安全的字符以及访问您可能事先不知道的密钥特别有用。