What's the purpose of the Infinity property? [closed]

荒凉一梦 提交于 2019-12-14 03:26:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!