大家好。
我有一个带有一些属性的 javascript 对象,比如说
function Animal() {
this.id;
this.name;
我需要以动态方式调用 id 函数来获取和设置它的值:像这样
Animal animal = new Animal();
var propertyName = "id";
animal.+propertyName = "name";
有没有一种优雅的方法来做到这一点?使用 jQuery?
亲切的问候
Massimo
除了对象语法之外,在 JavaScript 中您还可以使用类似数组的语法来查询对象属性。所以在你的情况下:
function Animal() { this.id; this.name };
Animal animal = new Animal();
animal.id = "testId";
var propertyName = "id";
alert(animal[propertyName]); // this should alert the value "testId";
这是一篇包含更多详细信息的文章:http://www.quirksmode.org/js/associative.html http://www.quirksmode.org/js/associative.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)