Javascript 将XML名称-值对动态转换为对象属性
如何向Javascript对象/类动态添加属性? 我正在解析一个xml文件,对于xml元素中的每个名称-值对,我试图将该对作为属性添加到Javascript对象中。请参见我的示例以了解更多信息:Javascript 将XML名称-值对动态转换为对象属性,javascript,xml,parsing,dynamic,Javascript,Xml,Parsing,Dynamic,如何向Javascript对象/类动态添加属性? 我正在解析一个xml文件,对于xml元素中的每个名称-值对,我试图将该对作为属性添加到Javascript对象中。请参见我的示例以了解更多信息: function MyObject(nType) { this.type = nType; } MyObject.prototype.parseXMLNode( /*XML Node*/ nodeXML ) { var attribs = nodeXML.attributes; f
function MyObject(nType)
{
this.type = nType;
}
MyObject.prototype.parseXMLNode( /*XML Node*/ nodeXML )
{
var attribs = nodeXML.attributes;
for (var i=0; i<attribs.length; i++)
this.(attribs[i].nodeName) = attribs[i].nodeValue; // ERROR here
}
// Where the xml would look like
<myobject name="blah" width="100" height="100"/>
函数MyObject(nType)
{
this.type=nType;
}
MyObject.prototype.parseXMLNode(/*XML节点*/nodeXML)
{
var attribs=nodeXML.attributes;
对于(var i=0;i您已经非常接近了。要动态调用和分配对象上的属性,您需要使用括号表示法
例如:
person = {}
person['first_name'] = 'John'
person['last_name'] = 'Doe'
// You can now access the values using:
// person.first_name OR person['last_name']
以下内容适用于您:
MyObject.prototype.parseXMLNode( nodeXML ) {
var attrs = nodeXML.attributes,
length = attrs.length;
for(var i=0; i < length; i++) {
this[attrs[i].nodeName] = attrs[i].nodeValue;
}
}
MyObject.prototype.parseXMLNode(nodeXML){
var attrs=nodeXML.attributes,
长度=属性长度;
对于(变量i=0;i