Checking if a variable is an integer in javascript

后端 未结 3 1689
Happy的楠姐
Happy的楠姐 2020-12-20 22:43

I made a form where the user inputs values for width and height that they want for the pop up window to be. I am using window.open for that.

So I thin

相关标签:
3条回答
  • 2020-12-20 23:25

    An alternative answer if you worry about performance.

    var isInteger1 = function(a) {
        return ((typeof a !== 'number') || (a % 1 !== 0)) ? false : true;
    };
    

    Load test results compared to Zafer's answer in Chrome:

    undefined => 4ms vs 151ms
    1 => 10ms vs 390ms
    1.1 => 61ms vs 250ms
    '1' => 8ms vs 334ms
    [1] => 9ms vs 210ms
    {foo: 'bar'} => 8ms vs 478ms
    

    See for yourself: jsfiddle

    0 讨论(0)
  • 2020-12-20 23:33

    This is an answer to question mentioned in the topic, not the actual one in the body of the text :).

    The following method is more accurate on determining if the string is a real integer.

    function isInteger(possibleInteger) {
        return /^[\d]+$/.test(possibleInteger)​;
    }
    

    Your current method validates "7.5" for instance.

    EDIT: Based on machineghost's comment, I fixed the function to correctly handle arrays. The new function is as follows:

    function isInteger(possibleInteger) {
            return Object.prototype.toString.call(possibleInteger) !== "[object Array]" && /^[\d]+$/.test(possibleInteger);
    }
    
    0 讨论(0)
  • 2020-12-20 23:44
    var isWidthAnInteger = isInteger(document.getElementById('width').value);
    var isHeightAnInteger = isInteger(document.getElementById('height').value);
    if (isWidthAnInteger && isHeightAnInteger) {
        // TODO: window.open
    }
    

    where you have the following textboxes:

    Width: <input type="text" id="width" name="width" />
    Height: <input type="text" id="height" name="height" />
    
    0 讨论(0)
提交回复
热议问题