动态对象属性javascript [英] dynamic object properties javascript

查看:66
本文介绍了动态对象属性javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码块有问题:

var name = "";
var nutrients = {};
var tds = document.getElementById('data').getElementsByTagName('td');

name = tds[0].innerHTML;
nutrients[name].val = tds[1].innerHTML;
alert(nutrients.Energy.val);

如果我取出 .val 这两行代码均有效。我试图通过从表格中提取信息来动态创建
营养素。 能量和所有50种营养素名称必须具有值和单位属性。最终,这将是一个循环。

If I take out the .val on both lines, the code works. I'm trying to dynamically create the " nutrients" abject by extracting information from a table. "Energy", and all 50 of nutrient names must have a "value" and a "unit" property. Eventually this will be a loop.

感谢您的帮助

推荐答案

尝试分配

nutrients[name].val = tds[1].innerHTML;

营养物对象仍然为空,并且营养物[能量] (或其他)将不确定。 beeing分配属性时引发异常。而是使用

the nutrients object is still empty, and nutrients["Energy"] (or whatever) will be undefined; throwing an exception when beeing assigned a property. Instead, use

nutrients[name] = {
    val: tds[1].innerHTML
};

这篇关于动态对象属性javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆