如果给定参数是方形数,JavaScript中测试的最佳方法是什么? [英] What's the best way in JavaScript to test if a given parameter is a square number?
本文介绍了如果给定参数是方形数,JavaScript中测试的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个函数,用于测试给定参数是否为方数。
I created a function that will test to see if a given parameter is a square number.
在此处阅读方形数字: https:/ /en.wikipedia.org/?title=Square_number
Read about square numbers here: https://en.wikipedia.org/?title=Square_number
如果数字是方形数字,则返回 true ,否则返回假。负数也会返回 false 。
If the number is a square number, it returns true and otherwise false. Negative numbers also return false.
示例:
isSquare(-12) // => false
isSquare( 5) // => false
isSquare( 9) // => true
isSquare(25) // => true
isSquare(27) // => false
现在,我正在使用这种方法: http://jsfiddle.net/marcusdei/ujtc82dq/5/
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?
推荐答案
试试这个:
var isSquare = function (n) {
return n > 0 && Math.sqrt(n) % 1 === 0;
};
- 检查数字是否为正
- 检查
sqrt
是否为完整数字,即整数
- Check if number is positive
- Check if
sqrt
is complete number i.e.integer
这篇关于如果给定参数是方形数,JavaScript中测试的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文