Introduction of javascript Number and Math Objects

  • 2021-12-05 05:30:37
  • OfStack

Directory 1. Number2 in javascript. Math object in Javascript

1. Number in javascript

javascript The numeric type belongs to the original type. In addition to the common values we know in decimal, we can also use 0x for 106-ary integers, 0b for binary integers, and 0O for octal integers


0xa // Correspondence 10 Binary system  10

0b101 // Correspondence 10 Binary system  5

0o22  // Correspondence 10 Binary system  18

In javascript 0 can be used as a divisor, and the return value is infinity. This is very different from other languages. For example python 0 cannot be used as a divisor.


1/0   // Infinity

Infinity Indicates an infinite value

But the result of 0/0 is NaN , NaN It is also a numeric type, which is a numeric value of a special number, indicating that it is not a numeric value of a "numeric value".

When converting a non-numeric string to a numeric type, NaN is also returned, for example praseInt('a')

Can be used Number.isNaN Or global function isNaN Determine whether a value is NaN


Number.isNaN(2)  //false
Number.isNaN('a') // true
Number.isNan('2') //false


Numeric value is a primitive type and also has a corresponding wrapper object javascript0 , Number Class provides many methods, including the above-mentioned isNaN .


n = new Number(10)
n.valueOf() === 10   //true

The value of the object n defined by the wrapper class is exactly the same as the original type value 10.

2. Math object in Javascript

Math Object is Javascript The global object of, provides many methods of mathematical operation

Math. max Get the maximum value:


let max = Math.max(1,2,3,4)
console.log(max)  //4

Math. min Get the minimum value:


let min = Math.min(1,2,3,4)
console.log(min) //1

If you are looking for the maximum and minimum values in an array, you can use the extension operator... to solve the array into multiple parameter values


Math.max(...[1,2,3,4]) //4

Math. ceil rounding up:


console.log(Math.ceil(2.3)) // 3

Math. floor rounding down:


console.log(Math.floor(2.8)) // 2

Math. round 4 rounded by 5 rounded:


console.log(Math.round(2.5))  //3
console.log(Math.round(2.3))  //2


Math.random Randomly generate 1 floating point number between [0, 1], including 0 but not 1


1/0   // Infinity

0

Randomly generate an integer between 0 and 10


1/0   // Infinity

1

Math. pow power:


1/0   // Infinity

2

Related articles: