js之Math方法、字串方法、date例項
阿新 • • 發佈:2018-12-22
Math方法
Math是一個物件資料型別
在Math下有很多方法
console.log(Math);
console.log(typeof Math);
- Math.abs(): 取絕對值
- Math.floor(): 向下取整
console.log(Math.floor(4.9999));//4
console.log(Math.floor(-4.9999));//-5
- Math.ceil()向上取整
- Math.max() 獲取一組數的最大值
- Math.min() 獲取一組數的最小值
- Math.random() 產生一個[0,1)的隨機小數
- Math.round() :四捨五入
- 產生一個m-n之間的隨機整數
Math.round(Math.random()*(n-m)+m)
- Math.pow(m,n);獲取m的n次冪;
console.log(Math.pow(4, 4));
- Math.sqrt : 開平方
console.log(Math.sqrt(16));
字串方法
toUpperCase
: 把小寫字母變成大寫
原字串不變;toLowerCase
: 把大寫轉小寫charAt
: 通過索引獲取對應的字元
console.log(str[3]);
charCodeAt
: 獲取對應的字元的Unicode編碼值;
console.log(str.charCodeAt(3));
// 97-122 a-z 65-90 A-Z
substr(m,n)
: 字串擷取;從索引m開始,擷取n個;如果只有一個引數,擷取到末尾
console.log(str.substr(2));
substring(m,n)
;從索引m開始,擷取到索引n;但不包含n;slice(m,n)
;從索引m開始,擷取到索引n;但不包含n;slice 支援負數傳參;
console.log(str.slice(2, -5))
replace
: 替換replace(old,new);
用新字串替換舊字串indexOf
: 檢測字串第一次出現的索引位置,如果不存在,返回-1;lastIndexOf
:檢測字串最後一次出現的索引位置,如果不存在,返回-1;split
: 按照特定的字元分隔成陣列中的每一項;
console.log(str.split(" "));
concat
: 字串拼接;trim
:去字串的左右空格
trimLeft() 去掉字串左邊的空格
trimRight() 去掉字串右邊的空格
console.log(str.trimLeft());
console.log(str.length);
Date的例項
new + 函式: 建立這個函式的例項;例項是個物件資料型別;
new 是個關鍵字;
console.log(new Date());// 獲取當前電腦的系統時間;
var date = new Date();
console.log(date);//Wed Dec 19 2018 17:09:34 GMT+0800
getFullYear
: 返回時間年;
console.log(date.getFullYear());// 2018getMonth
:返回時間月【0-11】
console.log(date.getMonth());// 11getDate()
: 返回當前日 【1-31】
console.log(date.getDate());getDay
: 返回星期幾;【0-6】星期日是0;
console.log(date.getDay());
5.getHours
: 返回小時
console.log(date.getHours());// [0-23]getMinutes
: 返回時間的分鐘數
console.log(date.getMinutes());//[0-59]getSeconds
: 獲取時間秒
console.log(date.getSeconds());getMilliseconds
: 獲取毫秒數
console.log(date.getMilliseconds());//[0-999]
//console.log(typeof date);// "object"
console.log(date.getTime());// 當前時間距離1970-1-1上午8:00 毫秒差
console.log(Date.now());// 經常用於產生一個時間戳;產生一個唯一的數字;