开发者

Stumped: Javascript Comparison Error

开发者 https://www.devze.com 2023-04-10 16:39 出处:网络
I\'m writing a plotting/graphing library for Javascript and came across what seems to be a huge issue.

I'm writing a plotting/graphing library for Javascript and came across what seems to be a huge issue.

I have 4 number inputs for defining the minimum and m开发者_运维技巧aximum values that the graph will display, much like on a TI-84 graphing calculator: XMin, XMax, YMin, YMax.

<div id="window">
    <input type="number" class="bound" id="minX" value="" />
    <input type="number" class="bound" id="maxX" value="" />
    <br />
    <input type="number" class="bound" id="minY" value="" />
    <input type="number" class="bound" id="maxY" value="" />
</div>

Then I have code that grabs these values and puts them into the function Plot.setBounds(xMin, xMax, yMin, yMax) whenever they are modified:

var plot1 = new Plot();
$('#window .bound').change(function() {
    var minX = $('#window #minX').val(),
        maxX = $('#window #maxX').val(),
        minY = $('#window #minY').val(),
        maxY = $('#window #maxY').val();
    console.log('modified to:', minX, maxX, minY, maxY);
    plot1.setBounds(minX, maxX, minY, maxY);
    plot1.draw();
});

Finally, for the Plot.setBounds(xMin, xMax, yMin, yMax) function, I have:

Plot.prototype.setBounds = function (xMin, xMax, yMin, yMax) {
    if ((xMin < xMax) && (yMin < yMax)) {
        this.bounds = [[xMin, xMax], [yMin, yMax]];
    } else {
        console.error('Plot.setBounds(xMin, xMax, yMin, yMax) requires maximum values that are greater than the minimum values!');
        console.log('received:', xMin, xMax, yMin, yMax);
    }
    return this;
};

The problem arises, however, when xMin >= 2 and xMax >=10, where an error is thrown into the console because for some reason the comparison returned false. You can check the numbers given before and after the error (modified to and received), and they will have the same values.

Another peculiar fact is how when the computation for the same numbers is put into the console by hand, the comparison returns true. This makes me believe it has something to do with the calling of the function.

It is also interesting to note how the problem only occurs when xMin >= 2 and xMax >= 10.

I have a preview you can test here: http://dl.dropbox.com/u/962292/web/plot.js/static.html

I'd be infinitely grateful if you could find a solution to my situation.


You have strings and need numbers:

var minX = +$('#minX').val(),
    maxX = +$('#maxX').val(),
    minY = +$('#minY').val(),
    maxY = +$('#maxY').val();

+ is a simple quick conversion to a number. And IDs are unique to #window is irrelevant.

For example, "9" > "19"; // true


Another way to get a number is with parseInt().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号