Detailed explanation of JavaScript built-in object Math

Detailed explanation of JavaScript built-in object Math

1. There are three types of JavaScript objects: custom objects (learned before, basic), browser objects (learned by API), and built-in objects (basic)

2. Built-in objects: some of the objects that come with the JavaScript language are for developers to use, and provide the most commonly used and basic properties and methods (Math, Array, Date, String, etc.)

3. Math object: is a built-in object with properties and methods of mathematical constants and functions, not a function object

Four. Related methods about Math

  • Math.max() is a method that returns the maximum value in a set of data
console.log(Math.max(1,3,2,6,4,9,6));  //9
  • Math.PI is an attribute that returns the pi
console.log(Math.PI);  //3.141592653589793
  • Math.min() is a method that returns the minimum value in a set of data
console.log(Math.min(1,3,2,6,4,9,6));  //1
  • Math.abs() is a method that returns the absolute value of the data
console.log(Math.abs(-10));  //10
  • Math.floor() round down to the smallest
console.log(Math.floor(3.14)); //3
  • Math.ceil() round up to the largest
console.log(Math.ceil(3.14)); //4
  • Math.round() rounding
console.log(Math.round(3.14));  //3
  • Math.random() returns a random decimal (the range of decimals is greater than 0 and less than 1)
console.log(Math.random());  //0.42735326161223

V. Case
Requirements: Get a random integer between two numbers, and include these two numbers

var min, max;  //定义最大数和最小数
Math.floor(Math.random() * (max - min + 1)) + min;  //返回最大数和最小数之间的随机整数,并且包含最大数和最小数

It is more convenient to encapsulate the above code into a function to use

function getNum(min,max){
	return Math.floor(Math.random() * (max-min+1)+min);
}

Guess you like

Origin blog.csdn.net/Angela_Connie/article/details/110296036