What's the best way in JavaScript to test if a

2019-04-06 05:07发布

I created a function that will test to see if a given parameter is a square number.

Read about square numbers here: https://en.wikipedia.org/?title=Square_number

If the number is a square number, it returns true and otherwise false. Negative numbers also return false.

Examples:

isSquare(-12) // => false
isSquare( 5) // => false
isSquare( 9) // => true
isSquare(25) // => true
isSquare(27) // => false

Right now, I am using this method: http://jsfiddle.net/marcusdei/ujtc82dq/5/

But, is there a shorter more cleaner way to get the job done?

2条回答
Viruses.
2楼-- · 2019-04-06 05:18

I would definitely go for:

var isSquare = function (n) {
    return Math.sqrt(n) % 1 === 0;
};

PS: 0 is a square number for those who wonder

Demo

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-04-06 05:33

Try this:

var isSquare = function (n) {
    return n > 0 && Math.sqrt(n) % 1 === 0;
};
  1. Check if number is positive
  2. Check if sqrt is complete number i.e. integer

Demo

查看更多
登录 后发表回答