Mittwoch, 13. November 2013

JavaScript parseInt is sometimes not enough!


after 2 hours I finally figured out, that you can not rely on a single parseInt(...), see

http://jsfiddle.net/8pPL9/9/

parseInt is used the first time during reading values from table in JS line 18

comment out JS line 27 and activate JS line 29 and you will see, that the value comparison still works with string insteadt of int values


Test-Code from jsfiddle

<div id="table_div">
    <table border="1">
        <tr><td>Value 1</td><td>2</td></tr>
        <tr><td>Value 2</td><td>3</td></tr>
        <tr><td>Value 3</td><td>10</td></tr>
    </table>
</div>

var tableEl = document.getElementById("table_div").getElementsByTagName("table")[0];
var rowsEl = tableEl.getElementsByTagName("tr");
var chartDatasetData = [];
for ( var r = 0; r < rowsEl.length; r++ ){
    //log("in row " + r);
    var columnsEl = rowsEl[r].getElementsByTagName("td");
    for ( var c = 0; c < columnsEl.length; c++ ){
        //log("in col " + r);
        if(c > 0){
            var columnData = chartDatasetData[c-1];
            if( columnData == undefined ){
                chartDatasetData[c-1] = [];
            }
            var columnRowData = chartDatasetData[c-1][r];
            if( columnRowData == undefined ){
                chartDatasetData[c-1][r] = [];
            }
            var iValue = parseInt(columnsEl[c].innerHTML);
            log("pushing value " + iValue + " to " + (c-1) + "," + r);
            chartDatasetData[c-1][r].push(iValue);
        }
    }
}
var newData = [];
for (var j=0; j<chartDatasetData[0].length; j++){
    //data has to be casted to int again!!
    newData.push(parseInt(chartDatasetData[0][j]));
    // this will not work
    //newData.push(chartDatasetData[0][j]);
}

var upperValue2 = Number.MIN_VALUE;
var lowerValue2 = Number.MAX_VALUE;
for (var j=0; j<newData.length; j++){
    log(newData[j] + ">" + upperValue2 + " = " + (newData[j] > upperValue2));
    if ( newData[j] > upperValue2) {
        upperValue2 = newData[j]
    };
    log(newData[j] + "<" + lowerValue2 + " = " + (newData[j] < lowerValue2));
    if ( newData[j] < lowerValue2) {
        lowerValue2 = newData[j]
    };
}
log("Table-Values: min " + lowerValue2 + ", max " + upperValue2);

function log(msg){
    document.getElementById("log").innerHTML = document.getElementById("log").innerHTML + msg + "<br/>";
}

0 Kommentare:

Kommentar veröffentlichen