javascript - 带有变量的 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。有谁知道解决这个问题的方法?
解决方案
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())
继续阅读:
推荐阅读
- lua - 单击 Gui 按钮时如何制作替换图像&
- selenium - 这是 Cucumber 中 table.raw 的当前方法
- windows - inno setup:使用 devcon 安装 MS Loopback 适配器?
- python - Pandas - 使用将 2 行合并为 1 行
- gatsby - 如何格式化代码片段
使用 Contentful 的富文本反应渲染器的标签?
- sql-server - 我无法在 where 子句中使用 case 语句来处理参数
- reactjs - 测试具有 api 调用的 redux-saga 函数
- python - 如何为正整数场设置最大值
- java - FCM 无效的主题名称。Base64 生成带有无效字符的字符串
- c# - 获取错误消息未找到存储过程