今天這篇給大家介紹一下Javascript中的一個內置對象-Math
數學對象,很簡單,直接使用即可,不用設置,沒有邏輯,記住就可以了
方法或屬性:
屬性:Math.PI圓周率
console.log(Math.PI);//3.141592653589793
var r = 100;
console.log(Math.PI * r * r) ;//31415.926535897932
console.log(2*2*Math.PI.toFixed(3))//12.568結果保留了三位小數
方法:
Math.round方法用於四捨五入
console.log(Math.round(45.678))// 46
console.log(Math.round(45.378))//45
console.log(Math.round(-45.678))//-46
隨機數:0~1,不包括0和1
console.log(Math.random());
Math.abs方法返回參數值的絕對值。
Math.abs(1) // 1
Math.abs(-1) // 1
Math.max方法返回參數之中最大的那個值,Math.min返回最小的那個值。如果參數爲空, Math.min返回Infinity, Math.max返回-Infinity。
Infinity 用於存放表示正無窮大的數值
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity
Math.floor方法小於參數值的最大整數(地板值)。
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
Math.ceil方法返回大於參數值的最小整數(天花板值)
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
Math.pow方法返回以第一個參數爲底數、第二個參數爲冪的指數值。
// 等同於 2 ** 2
Math.pow(2, 2) // 4
// 等同於 2 ** 3
Math.pow(2, 3) // 8
Math.sqrt方法返回參數值的平方根。如果參數是一個負值,則返回NaN。
Math.sqrt(4) // 2
Math.sqrt(-4) // NaN
max和min接收的是多個參數,不是一個數組,也不能接收一個數組,強行寫,會得到NaN
console.log(Math.max(34,56,37,24,89,13)); // 89
console.log(Math.min(34,56,37,24,89,13)); // 13
console.log(Math.min([34,56,37,24,89,13])); // NaN
sin和cos方法接收的是弧度,不是角度
90的角度
console.log(Math.sin( Math.PI / 180 * 90 ));//1
console.log(Math.cos( Math.PI / 180 * 90 ));//6.123233995736766e-17
計算斜邊
console.log(Math.sqrt(3*3+4*4))//5
註釋:Math 對象並不像 Date 和 String 那樣是對象的類,因此沒有構造函數 Math(),像 Math.sin() 這樣的函數只是函數,不是某個對象的方法。您無需創建它,通過把 Math 作爲對象使用就可以調用其所有屬性和方法。
新人初來,有很多欠缺需要大家多多指教,逆疫而戰大家加油