当前位置:网站首页>ES6: Expansion of Numerical Values

ES6: Expansion of Numerical Values

2022-08-11 09:20:00 no tide

Number.isFinite() and Number.isNaN()

ES6 provides new methods Number.isFinite() and Number.isNaN() on the Number object.


Number.isFinite()

Number .isFinite() is used to check if a number is finite, i.e. not Infinity.

Note, if the parameter type is not numeric, Number .isFinite() will always return false

Number.isFinite(15); // trueNumber.isFinite(0.8); // trueNumber.isFinite(NaN); // falseNumber.isFinite(Infinity); // falseNumber.isFinite(-Infinity); // falseNumber.isFinite('foo'); // falseNumber.isFinite('15'); // falseNumber.isFinite(true); // false

Number.isNaN()

Number.isNaN() Used to check if a value is NaN

Note: If the parameter type is not NaN, Number.isNaN will always beReturns false.

Number.isNaN(NaN) // trueNumber.isNaN(15) // falseNumber.isNaN('15') // falseNumber.isNaN(true) // falseNumber.isNaN(9/NaN) // trueNumber.isNaN('true' / 0) // trueNumber.isNaN('true' / 'true') // true

Differences from traditional methods

They are the same as the traditional global methods isFinite() and isNaN()The difference is that the traditional method calls   Number() converts non-numeric values ​​to numeric values,Then judge, and these two new methods are only valid for numerical values, Number.isFinite()For non-numeric values, always return false, Number.isNaN() is only returned for NaNtrue, not NaNAlways return false.

isFinite(25) // trueisFinite("25") // trueNumber.isFinite(25) // trueNumber.isFinite("25") // falseisNaN(NaN) // trueisNaN("NaN") // trueNumber.isNaN(NaN) // trueNumber.isNaN("NaN") // falseNumber.isNaN(1) // false

Number.parseInt(), Number.parseFloat()

ES6 places the global methods parseInt() and   parseFloat(), ported to Number object, the behavior remains completely unchanged.

The purpose of this is to gradually reduce global methods and make the language gradually modular.

// ES5 writingparseInt('12.34') // 12parseFloat('123.45#') // 123.45// ES6 writingNumber.parseInt('12.34') // 12Number.parseFloat('123.45#') // 123.45
Number.parseInt === parseInt // trueNumber.parseFloat === parseFloat // true

If there are any mistakes in the article, I urge you to ask questions, I would greatly appreciate it.If you don't understand, you can comment and I will reply.

If the article is helpful to everyone, I hope everyone can give it a thumbs up and encouragement, and everyone will work together in the future. The road is long, and the road is long and long

原网站

版权声明
本文为[no tide]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/223/202208110857082734.html