繁体   English   中英

带变量的Javascript参考对象属性

[英]Javascript Reference Object Attribute With Variable

我有一个具有多个属性的对象Node和一个用这些属性的名称填充的属性数组。 我想经历一个for循环,并使用该节点的属性值填充表单。 代码如下:

function Node(parentNode, nodeID, fields, type){
    this.id =  nodeID;
    this.fields = fields;
    this.parent = parentNode;
    this.type = type;
    this.firstChild = null;
    this.lastChild = null;
    this.previousSibling = null;
    this.nextSibling = null;
}

var runTerminalNode = function(node, count){
    var form = document.createElement('form');
    form.setAttribute('method', 'GET');
    form.setAttribute('action', '/table/');
    form.setAttribute('target', '_blank');

    var attributes = ['id', 'fields', 'type']

    for (i in attributes){
        var input = document.createElement('input');
        input.type = 'hidden';
        input.name = attributes[i];
        input.value = node.attributes[i];
        form.appendChild(input);
    }
}

var nodeObject = allNodes[nodeID];
runTerminalNode = (nodeObject, 0);

其中allNodes是一个映射,其中nodeID是键,而Node对象是值。

我收到的错误是“无法读取未定义的属性'0'”,因为node.attributes解析为未定义,并且它试图读取未定义数组中的第一个对象。 我想要的是将其读取为node.id,node.fields和node.type。 有谁知道解决这个问题的方法?

 for (i in attributes){

这将遍历数组 (0、1、2),它们不是对象的一部分。 另外, i是一个全局变量,由于各种原因它是不好的。 下一个问题在这里:

node.attributes[i]

这会在节点node中寻找属性的位置i处的值的“ attribute”属性,即:

node[ attributes[i] ]

相反,可以遍历值并声明变量:

for(const attr of attributes)
  console.log(node[attr]);

如果您真的想遍历索引,请执行以下操作:

for(const index of array.keys())
// OR
for(const [index, value] of array.entries())

继续阅读:

迭代数组

点符号与括号符号

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM