问题
Accidentally faced an Infinity property in JavaScript an wondered where in that world it can be used? Any real life example please.
回答1:
I'm assuming you're asking about why there's an Infinity
global property, not why there's a concept of having infinities in the first place, which is another matter.
It allows easy comparison with the Infinity
value itself, where you get it from some arithmetic:
function inv(x) {
return x * 100000000000;
}
inv(1e999) === Infinity;
This is especially useful as 1 / 0
is not equal to Infinity
in mathematics, so it's not obvious that you can use 1 / 0
.
If you want a numeric comparison to always return true, and you're using a variable, you can set the variable to Infinity to always force the condition to be true. Take this example:
var a = Infinity; // some number from elsewhere
var arr = [];
function foo(maxLen) {
if (arr.length < maxLen) arr.push(1);
}
foo(a); // you can't change the function
This could be useful in cases where you can't change the comparison statement used.
回答2:
Here is another real life example:
var x = +prompt('Enter x:'),
y = +prompt('Enter y:'),
value = Math.pow(x, y);
if (value === Infinity || value === -Infinity) {
console.log('The value is too large!');
}
As an example, if the entered values are 1e100
and 100
, the power method returns Infinity
.
回答3:
You can use it if you don't know what the minimum value of an array
or also a mathematical-function
is like this:
var minimum = Infinity;
var i = 0;
for(i = 0; i < array.length; i++) {
if(array[i] < minimum) {
// new minimum found
minimum = array[i];
}
}
alert("Minimum: " + minimum);
来源:https://stackoverflow.com/questions/23407009/whats-the-purpose-of-the-infinity-property