Javascript:如何访问名称为动态的属性? [英] Javascript: how to access property whose name is dynamic?

查看:295
本文介绍了Javascript:如何访问名称为动态的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript从其名称创建变量

代码下面检查javascript对象 form_errors 是否具有名称由 this.name 指定的属性,其中 this 指的是文本输入

The code below checks to see if the javascript object form_errors has the property whose name is specified by this.name, where this refers to a text input

if (form_errors.hasOwnProperty(this.name)) {
  alert(form_errors.<this.name>;
}

如何在不对硬件名称进行硬编码的情况下访问该属性,广义形式 this.name ?谢谢。

How can I access the property without hard-coding the property name but leaving in the generalized form this.name ? Thanks.

推荐答案

使用括号:

form_errors[this.name]

您可以通过传入带有名称的字符串来访问对象的任何属性例如, foo.bar foo ['bar'] 具有相同的结果。

You can access any property of an object by passing in a string with its name. For instance, foo.bar and foo['bar'] have the same result.

这篇关于Javascript:如何访问名称为动态的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆