首页 > 解决方案 > 带有变量的 Javascript 引用对象属性

问题描述

我有一个对象节点,它具有多个属性和一个属性数组,其中填充了这些属性的名称。我想通过一个 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。有谁知道解决这个问题的方法?

标签: javascriptobject

解决方案


 for (i in attributes){

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

node.attributes[i]

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

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())

继续阅读:

迭代数组

点表示法与括号表示法


推荐阅读