encodeURI() 與 encodeURIComponent() 都用於編碼 URI,差別在處理範圍:
encodeURI() 不會編碼本身屬於 URI 結構一部分的特殊字元,例如冒號、正斜線、問號、井號等encodeURIComponent() 會把任何非標準字元都編碼進去,因此更適合用於編碼「查詢參數的值」把字串當成程式碼來執行:
var msg = "hello world";
eval("alert(msg)"); // hello world
威力很大,但強烈不建議使用。它會關閉引擎的編譯最佳化、帶來安全風險,也讓程式碼難以靜態分析。多數原本需要 eval 的場景,現在都能用 JSON.parse() 或正常的函式呼叫取代。
常數:
Math.E:自然對數底數 eMath.PI:圓周率 πMath.SQRT2:2 的平方根指數與對數:
Math.exp(num):e 的 num 次冪Math.log(num):num 的自然對數Math.pow(num, n):num 的 n 次冪Math.sqrt(num):num 的平方根絕對值:Math.abs(num)
三角與反三角:
Math.acos(x)、Math.asin(x)、Math.atan(x)Math.atan2(y, x):y/x 的反正切,能正確判斷象限Math.cos(x)、Math.sin(x)、Math.tan(x)注意三角函式的參數是弳度而非度數,需要時得自己換算。
var max = Math.max(3, 45, 67, 32); alert(max); // 67 var min = Math.min(2, 46, 74); alert(min); // 2
若數字來自陣列,可以搭配展開語法:Math.max.apply(null, arr) 或 Math.max(...arr)。
alert(Math.ceil(25.1)); // 26,無條件進位 alert(Math.ceil(25.5)); // 26 alert(Math.ceil(25.9)); // 26 alert(Math.round(25.1)); // 25,四捨五入 alert(Math.round(25.5)); // 26 alert(Math.round(25.9)); // 26 alert(Math.floor(25.1)); // 25,無條件捨去 alert(Math.floor(25.5)); // 25 alert(Math.floor(25.9)); // 25
負數時要特別小心:Math.round(-25.5) 得到 -25(往正無窮方向),而 Math.floor(-25.5) 得到 -26。若你需要的是「朝零方向取整」,得用 Math.trunc()。
Math.random() 回傳一個介於 0 與 1 之間的隨機數(不含 0 與 1)。要取得某個整數範圍內的隨機值,公式是:
隨機數 = Math.floor(Math.random() * 總數 + 第一個值) // 總數 = 第二個值 - 第一個值 + 1
封裝成函式:
function selectFrom(lowerValue, upperValue) {
var count = upperValue - lowerValue + 1;
return Math.floor(Math.random() * count + lowerValue);
}
var num = selectFrom(2, 10);
alert(num); // 介於 2 到 10 之間(含 2 與 10)
那個 + 1 是最容易漏掉的一項——少了它,範圍的上界永遠不會被抽到。