dynamic object properties javascript

穿精又带淫゛_ 提交于 2020-01-16 10:38:11

问题


Having issues with this code block:

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

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.

Thanks for any help


回答1:


When trying to assign

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

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
};


来源:https://stackoverflow.com/questions/15118525/dynamic-object-properties-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!