dynamic object properties javascript

2019-09-20 03:20发布

问题:

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