1. 程式人生 > >js之Math方法、字串方法、date例項

js之Math方法、字串方法、date例項

Math方法

Math是一個物件資料型別

在Math下有很多方法
console.log(Math);
console.log(typeof Math);

  1. Math.abs(): 取絕對值
  2. Math.floor(): 向下取整
console.log(Math.floor(4.9999));//4
console.log(Math.floor(-4.9999));//-5
  1. Math.ceil()向上取整
  2. Math.max() 獲取一組數的最大值
  3. Math.min() 獲取一組數的最小值
  4. Math.random() 產生一個[0,1)的隨機小數
  5. Math.round() :四捨五入
  6. 產生一個m-n之間的隨機整數
Math.round(Math.random()*(n-m)+m)
  1. Math.pow(m,n);獲取m的n次冪;
    console.log(Math.pow(4, 4));
  1. Math.sqrt : 開平方
    console.log(Math.sqrt(16));

字串方法

  1. toUpperCase : 把小寫字母變成大寫
    原字串不變;
  2. toLowerCase : 把大寫轉小寫
  3. charAt : 通過索引獲取對應的字元
console.log(str[3]);
  1. charCodeAt : 獲取對應的字元的Unicode編碼值;
console.log(str.charCodeAt(3));
// 97-122  a-z  65-90 A-Z
  1. substr(m,n) : 字串擷取;從索引m開始,擷取n個;如果只有一個引數,擷取到末尾
console.log(str.substr(2));
  1. substring(m,n);從索引m開始,擷取到索引n;但不包含n;
  2. slice(m,n);從索引m開始,擷取到索引n;但不包含n;slice 支援負數傳參;
console.log(str.slice(2, -5))
  1. replace : 替換replace(old,new);用新字串替換舊字串
  2. indexOf : 檢測字串第一次出現的索引位置,如果不存在,返回-1;
  3. lastIndexOf:檢測字串最後一次出現的索引位置,如果不存在,返回-1;
  4. split: 按照特定的字元分隔成陣列中的每一項;
console.log(str.split(" "));
  1. concat : 字串拼接;
  2. 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
  1. getFullYear : 返回時間年;
    console.log(date.getFullYear());// 2018
  2. getMonth :返回時間月【0-11】
    console.log(date.getMonth());// 11
  3. getDate() : 返回當前日 【1-31】
    console.log(date.getDate());
  4. getDay: 返回星期幾;【0-6】星期日是0;
    console.log(date.getDay());
    5.getHours : 返回小時
    console.log(date.getHours());// [0-23]
  5. getMinutes: 返回時間的分鐘數
    console.log(date.getMinutes());//[0-59]
  6. getSeconds: 獲取時間秒
    console.log(date.getSeconds());
  7. 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());// 經常用於產生一個時間戳;產生一個唯一的數字;