Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách kiểm tra biến là số nguyên (integer) trong JavaScript

ES6: Number.isInteger(value) – chính xác, không ép kiểu. Cách cũ: value === parseInt(value, 10).

Ví dụ

<!DOCTYPE html>
<html>
<head>
    <script>
        function checkInt(val) {
            if (Number.isInteger(val)) {
                alert(val + " là số nguyên!");
            } else {
                alert(val + " KHÔNG phải số nguyên!");
            }
        }
        // Test
        checkInt(10);      // Integer
        checkInt(10.0);    // Integer (10.0 === 10)
        checkInt(10.5);    // Not integer
        checkInt("10");    // Not integer (string)
        checkInt(NaN);     // Not integer
        checkInt(Infinity); // Not integer
    </script>
</head>
<body></body>
</html>

Polyfill cho trình duyệt cũ:

Number.isInteger = Number.isInteger || function(value) {
    return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
};