JavaScript 如何检查一个数字是否为无穷大
任务是通过JavaScript判断一个数字是否为无穷大。下面讨论了一些技巧。
方法1
检查数字是否等于Number.POSITIVE_INFINITY或Number.NEGATIVE_INFINITY。
示例: 这个示例使用了上面讨论的方法。
<body style="text-align:center;">
id="body">
<h1 style="color:green;"
id="h1">
GeeksForGeeks
</h1>
<h3>
Check if number is Infinity?
</h3>
<p id="GFG_UP"
style="font-size: 15px;
font-weight: bold;">
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
var up=document.getElementById('GFG_UP');
var down=document.getElementById('GFG_DOWN');
var n=1/0;
up.innerHTML="Click on the button to check if"+
" Number evaluates to Infinity.<br> Number = 1/0";
function GFG_Fun() {
if(n==Number.POSITIVE_INFINITY||n==Number.NEGATIVE_INFINITY) {
down.innerHTML="Infinity";
} else {
down.innerHTML="Not Infinity";
}
}
</script>
</body>
HTML
输出:
方法2
使用 Number.isFinite() 方法 来检查数字是否有限。
示例: 此示例使用上面讨论的方法。
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<h3>
Check if number is Infinity?
</h3>
<p id="GFG_UP" style="font-size: 15px;
font-weight: bold;">
</p>
<button onclick="GFG_Fun()">
click here
</button>
<p id="GFG_DOWN"
style="color:green;
font-size: 20px;
font-weight: bold;">
</p>
<script>
var up=document.getElementById('GFG_UP');
var down=document.getElementById('GFG_DOWN');
var n=1/4;
up.innerHTML="Click on the button to check if"+
" Number evaluates to Infinity.<br> Number = 1/4";
function GFG_Fun() {
if(!Number.isFinite(n)) {
down.innerHTML="Infinity";
} else {
down.innerHTML="Not Infinity";
}
}
</script>
</body>
HTML
输出: