9

I am very new to javascript as I am currently making a cross platform web app in jQuery Mobile, I have used the example of XML Parsing to a HighCharts graph yet when I encounter a null in my series data it fails to draw any of the line and makes it into a scatter plot almost.

// push data points
$(series).find('data point').each(function(i, point) {
    seriesOptions.data.push( 
        parseFloat($(point).text())
    );
});

I have no idea how to write a if statement that checks to see if it found a null and if so how to tell it to use it... Can anyone please help or point me in the right direction as I would love my charts to be correct rather than placing a zero value where I have a null.

Palendrone
  • 363
  • 1
  • 2
  • 14

3 Answers3

9

Well, parseFloat will return 'NaN' if it's not a number (null and undefined are NaNs) so you could try doing like this:

// push data points
$(series).find('data point').each(function(i, point) {
    var floatVal = parseFloat($(point).text());
    if (!isNaN(floatVal)) {
        seriesOptions.data.push(floatVal);
    }
});
Björn Roberg
  • 2,275
  • 2
  • 15
  • 15
  • Thank you for the reply Bjorn - I have put this in place and it works but not quite as intended for the charting, I need the value that comes back to reference either a number or the word null for HighCharts to plot a blank where the null lies. Would this then require converting the NaN to a null or am I completely way off? I have heard of isNull before but not isNaN... – Palendrone Mar 18 '13 at 16:03
1

A null check in JavaScript if just like any other C-style language:

 if (thing == null) 

Or

 if (thing != null)

I find this works well in most cases against my own programming where I'm writing as I would in, say, C#; however I find other peoples code relies on things never having been declared or set and such and so, and, all in all, it boils down to a spaghetti of checking for null and "undefined" - yes, the literal string, really - and whatever else.

Grant Thomas
  • 44,454
  • 10
  • 85
  • 129
  • Many thanks for your reply, what you have put makes some sense but I am really at a loss as to where this fits in with where I need to check for the null in my code - as I say I am very new to this and so far managed to piece what I need together to get to the end result. Would you be so kind as to help me where it goes with the function outlined? – Palendrone Mar 18 '13 at 15:33
0

With a quick google on Javascript If statments I beleive I have got there - thanks Bjorn :0) Your answer led me to get there !!!

// push data points
$(series).find('data point').each(function(i, point) {
    var floatVal = parseFloat($(point).text());
            if (!isNaN(floatVal)) {
                seriesOptions.data.push(floatVal);
        }
        else {
        seriesOptions.data.push(null);
        }
        console.log(floatVal)
    });
Palendrone
  • 363
  • 1
  • 2
  • 14