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

Date

获取某月的天数

下一月的第0天就是当前月的最后一天。

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」订阅
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值