乐闻世界logo
搜索文章和话题

How to check if a variable is an integer in JavaScript?

1个答案

1

In JavaScript, to check if a variable is an integer, you can use the Number.isInteger() function. This method returns a boolean indicating whether the given value is an integer. Here is an example:

javascript
let value = 5; console.log(Number.isInteger(value)); // Output: true value = 5.5; console.log(Number.isInteger(value)); // Output: false value = "5"; console.log(Number.isInteger(value)); // Output: false, because it is a string, even if the string represents an integer

In older versions of JavaScript or in environments that do not support Number.isInteger(), you can use a multi-step check to determine if a value is an integer:

  1. First, check if the variable is of a numeric type using the typeof operator.
  2. Then, use the modulus operator (%) to verify if the number has a fractional part.

For example:

javascript
function isInteger(value) { return typeof value === 'number' && value % 1 === 0; } console.log(isInteger(5)); // Output: true console.log(isInteger(5.5)); // Output: false console.log(isInteger('5')); // Output: false

This function isInteger first checks if value is of a numeric type, then uses % 1 to determine if it has a fractional part. If it is an integer, value % 1 should equal 0.

2024年6月29日 12:07 回复

你的答案