Ezra Ezra - 5 months ago 27
Javascript Question

Javascript for loop Uncaught TypeError from data attributes

I have a bunch of dataset's attached to some spans that I'm trying to loop through but keep getting the error:

dials.js:238 Uncaught TypeError: Cannot read property 'percentages' of undefined
.

My span structure is as follows:

<span class="dial rent"
data-name="Rent"
data-value="56"
data-marker="40"
data-min="0"
data-max="100"
data-percentages="0.25, 1">
</span>


My JS is:

var dials = document.getElementsByClassName('dial');

function createGauges() {
for (var key in dials) {
var data = dials[key].dataset;
var percent = data.percentages.split(',').map(Number);
console.log(percent);
newDial(data.name, data.value, data.marker, data.min, data.max, percent);
}
}


My data output structure looks like this:

DOMStringMap {name: "Cost of goods", value: "23", marker: "20", min: "0", max: "100"…}
marker:"20"
max:"100"
min:"0"
name:"Cost of goods"
percentages:"0.3, 1"
value:"23"


I'm stumped. When I log the
percent
variable I'm getting the correct data and it's outputting to my D3 graph. But the JS is erroring out and terminates so the rest of the data won't populate.

Answer

Actually for loog iterates over object's keys. In your case for loop goes over ["0", "length", "item", "namedItem"] keys for dials. So only valid one is 0. Look at the keys

for (var key in dials){
   console.log(key); // "0", "length", "item", "namedItem"
}

function createGauges() {
  Array.prototype.forEach.call(dials, function(dial){
    var data = dial.dataset;
    var percent = data.percentages.split(',').map(Number);
    console.log(percent);
    newDial(data.name, data.value, data.marker, data.min, data.max, percent);
  });
}