捋一捋容易被忽略的API用法

Date

獲取某月的天數

下一月的第0天就是當前月的最後一天。javascript

function daysInMonth(year, month) {
    let date = new Date(year, month + 1, 0);
    return date.getDate();
}

// 注意在JS裏月份是從0開始算的。下面算的是2017年3月份有多少天
console.log(daysInMonth(2017, 2)); // 31 
// 2017年2月有多少天
console.log(daysInMonth(2017, 1)); // 28
// 2016年2月有多少天
console.log(daysInMonth(2016, 1)); // 29複製代碼

Date.prototype.getTimezoneOffset - 獲取當地時間跟UTC時區的時間差,以分鐘爲單位。

let now = new Date(); 
console.log(now.toISOString()); //2017-08-05T13:16:35.363Z
//中國是東八區,北京時間是(GMT+08:00)
console.log(now.getTimezoneOffset()); // -480
//將本地時間換算成格林威治時間/零時區
let GMTDate = new Date(now.getTime() + now.getTimezoneOffset() * 60 * 1000);
console.log(GMTDate.toISOString()); //2017-08-05T05:16:35.363Z
//將本地時間換算成東3區時間
let eastZone3Date = new Date(GMTDate.getTime() + 3 * 60 * 60 * 1000);
console.log(eastZone3Date.toISOString()); //2017-08-05T08:20:55.235Z複製代碼

JSON

JSON.stringify(value[, replacer[, space]])

replacer是個函數的狀況 - 在stringify前對值進行操做

JSON.stringify({
    a: 4,
    b: [3, 5, 'hello'],
}, (key, val) => {
    if(typeof val === 'number') {
        return val * 2;
    }
    return val;
}); //{"a":8,"b":[6,10,"hello"]}複製代碼

replacer是個數組的狀況 - 對key值進行白名單過濾

JSON.stringify({
    a: 4,
    b: {
        a: 5,
        d: 6
    },
    c: 8
}, ['a', 'b']); //{"a":4,"b":{"a":5}}複製代碼

space能夠用來對輸出進行格式優化

JSON.stringify({
    a: [3,4,5],
    b: 'hello'
}, null, '|--\t');
/**結果: { |-- "a": [ |-- |-- 3, |-- |-- 4, |-- |-- 5 |-- ], |-- "b": "hello" } */複製代碼

Reference

Notice

  • 若是您以爲該Repo讓您有所收穫,請「Star 」支持樓主。
  • 若是您想持續關注樓主的最新系列文章,請「Watch」訂閱
相關文章
相關標籤/搜索