1. 程式人生 > 實用技巧 >js基礎 ---- 內建物件

js基礎 ---- 內建物件

今天我們來總結一下 JavaScript 常見的幾個內建物件和用途

一、Array 陣列物件

  (1)、push() 在陣列的尾部新增一個元素 返回陣列的新長度

      var arr = [1,2]

      var length = arr.push(3)

      console.log(var , length) // [1,2,3], 3

  (2)、unshift()在陣列的頭部新增一個元素 返回陣列的新長度

  (3)、pop() 刪除陣列尾部的最後一個元素 返回被刪除的元素(不管刪除還是新增都會改變陣列的長度

      var arr = [1,2,3]

      var a = arr.pop()

      console.log(arr, a) //[1,2] 3

  (4)、shift() 刪除陣列第一個元素 返回被刪除的元素 (不管刪除還是新增都會改變陣列的長度

  (5)、concat() 數組合並 合併後返回一個新陣列 原陣列不會變化

  (6)、splice(從什麼位置開始,刪除多少個元素,要插入的元素) 返回被刪除元素組成的新陣列

二、Math方法

  (1)、Math.floor()向下取整

     a=Math.floor(25.6);

    console.log(a); //25

  (2)、Math.ceil()向上取整  

    a=Math.floor(25.6);

    console.log(a); //26

  (3)、Math.round()四捨五入

    c=Math.round(25.5);

    console.log(c); //26

  

三、String 字串方法

   (1)、charAt()獲取下標位置的字元

      var str = 'abcd'

      var s = str.chatAt(1) //b

   (2)、charCodeAt()將下標位置的字元轉為Unicode編碼

   (3)、String.fromCharCode()將Unicode編碼轉為字串

   (4)、str.concat()字串拼接

   (5)、replace()替換一般與正則表示式一起使用

四、日期物件

  (1)、建立日期物件

    var date = new Date()

   date.getTime() //獲取時間戳是計算從1970年1月1日 00:00:00 到現在的毫秒數

  (2)、獲取日期 

    var date=new Date();
    date.getFullYear(); // 獲取年份
    date.getYear(); // 獲取的年份是從1900年開始計算的,有問題
    date.getMonth()+1; // 獲取月份 從0開始
    date.getDate(); // 獲取日期
    date.getDay(); // 獲取星期 從0開始 0就是星期日 1是星期1
    date.getHours(); // 獲取小時
    date.getMinutes(); // 獲取分鐘
    date.getSeconds(); // 獲取秒
    date.getMilliseconds();// 獲取毫秒
    console.log(date);

  (3)、設定日期時間 

    var date=new Date();
    date.setFullYear(2021);
    date.setMonth(12); // 1月,進位了年份+1 是從0開始的;
    date.setDate(40); // 設定進位了
    date.setHours(date.getHours() + 2); // 設定為現在時間的2小時後
    date.getUTCFullYear(); // 凡是帶有UTC都是格林尼治時間
    date.toString(); // 直接轉換為字串
    date.toLocaleString(); // 轉換為本地(windows上)設定格式時間字串
    date.toUTCString(); // 轉換為格林尼治時間字串
    console.log(date);

五、JSON 物件

  (1)、JSON.stringify()方法

    JSON.stringify()方法用於將JavaScript值轉換為JSON字串,返回包含JSON文字的字串。

    JSON.stringify(value,replacer)

    引數說明:

      value: 必需, 要轉換的 JavaScript 值(通常為物件或陣列)。

      replacer: 可選。用於轉換結果的函式或陣列。(如果 replacer 是一個數組,則僅轉換該陣列中具有鍵值的成員。成員的轉換順序與鍵在陣列中的順序一樣。)

    var jsonObj = {
        "title":"javascript",
        "group":{
            "a":1
        }
    };
    console.log(JSON.stringify(jsonObj,["group","a"])); // {"group":{"a":1}}

   (2)、JSON.parse()方法

     JSON.parse()方法用於將一個JSON字串轉換為物件,返回給定JSON字串轉換後的物件。

     JSON.parse(text, reviver)

     引數說明:

       text: 必需, 一個有效的JSON字串。

       reviver: 可選,一個轉換結果的函式, 將為物件的每個成員呼叫此函式。