最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

parsing - Javascript parseFloat and nulls - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Mar 18, 2013 at 13:56 PalendronePalendrone 3631 gold badge2 silver badges14 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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);
    }
});

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.

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)
    });
发布评论

评论列表(0)

  1. 暂无评论