SoFunction
Updated on 2025-02-28

Introduction to javascript Number and Math objects

1. Number in javascript

javascript numerical types belong to the original type. In addition to the normal values ​​expressed in decimal as we know, we can also use 0x to represent hexadecimal integers, 0b to represent binary integers, and 0O to represent octal integers.

0xa // Corresponding to decimal 10
0b101 //Complied with decimal system 5
0o22  // Corresponding to decimal 18

existjavascript, 0 can be regarded as a divisor, and the return value is infinite. This is very different from other languages. For examplepython0 cannot be used as a divisor.

1/0   // Infinity

Infinity Infinity value

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

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

Can be usedOr global functionsisNaN Determine whether a value isNaN

(2)  //false
('a') // true
('2') //false


The numeric value is a primitive type, and also has corresponding wrapping objects.NumberNumber The class provides many methods, including the above mentionedisNaN

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

The value corresponding to object n defined by the wrapper class is exactly equal to the original type value 10.

2. Math object in Javascript

MathThe object isJavascriptThe global object provides many mathematical operation methods

Get the maximum value:

let max = (1,2,3,4)
(max)  //4

Get the minimum value:

let min = (1,2,3,4)
(min) //1

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

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

Round upward:

((2.3)) // 3

Round downward:

((2.8)) // 2

Rounding:

((2.5))  //3
((2.3))  //2


Randomly generate a floating point number between [0, 1), including 0 but not 1

(())


Randomly generate an integer between 0 and 10

let num = (()*10)
(num)


Power:

(2, 10)  //1024

Here's the article aboutjavascript Number This is all about the article introducing the Math object, more relatedjavascript  NumberandMathFor content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!