Useful APIs that you probably don't notice

本文介绍了JavaScript中处理日期和JSON数据的一些实用方法,包括获取月份天数、时区转换、JSON字符串化时的筛选与美化等。通过具体示例展示了如何使用JavaScript内置函数解决实际问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Date

Get the number of days in a month

The 0th day of next month is the last day of the current month.

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

/**
 * Note that JS Date month starts with 0
 * The following computes how many days in March 2017
 */
console.log(daysInMonth(2017, 2)); // 31 
// how many days in Feb 2017
console.log(daysInMonth(2017, 1)); // 28
// how many days in Feb 2016
console.log(daysInMonth(2016, 1)); // 29

getTimezoneOffset - get the time zone difference, in minutes, from current locale (host system settings) to UTC.

let now = new Date(); 
console.log(now.toISOString()); //2018-03-12T01:12:29.566Z
// China is UTC+08:00
console.log(now.getTimezoneOffset()); // -480
// convert to UTC 
let UTCDate = new Date(now.getTime() + now.getTimezoneOffset() * 60 * 1000);
console.log(UTCDate.toISOString()); //2018-03-11T17:12:29.566Z
//convert to UTC+03:00
let eastZone3Date = new Date(UTCDate.getTime() + 3 * 60 * 60 * 1000);
console.log(eastZone3Date.toISOString()); //2018-03-11T20:12:29.566Z

JSON

[JSON.stringify(value[, replacer[, space]])](https://developer.mozilla.org...

When replacer is a function - apply replacer before stringify the value.

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"]}

when replacer is an array - use replacer as a white list to filter the keys

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

space can be used to beautify the output

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

String

[String.prototype.split([separator[, limit]])](https://developer.mozilla.org...

''.split('') // []

separator can be a regular expression!

'abc1def2ghi'.split(/\d/);  //["abc", "def", "ghi"]

If the seperator is a regular expression that contains capturing groups, the capturing groups will appear in the result as well.

'abc1def2ghi'.split(/(\d)/);  // ["abc", "1", "def", "2", "ghi"]

Tagged string literals

let person = 'Mike';
let age = 28;

function myTag(strings, personExp, ageExp) {
  let str0 = strings[0]; // "that "
  let str1 = strings[1]; // " is a "

  // There is technically a string after
  // the final expression (in our example),
  // but it is empty (""), so disregard.
  // var str2 = strings[2];

  let ageStr;
  if (ageExp > 99){
    ageStr = 'centenarian';
  } else {
    ageStr = 'youngster';
  }

  return str0 + personExp + str1 + ageStr;
}

let output = myTag`that ${ person } is a ${ age }`;
console.log(output);
// that Mike is a youngster

null vs undefined

If we don't want to distinguish null and undefined, we can use ==

undefined == undefined //true
null == undefined // true
0 == undefined // false
'' == undefined // false
false == undefined // false

Don't simply use == to check for the existence of a global variable as it will throw ReferenceError. Use typeof instead.

// a is not defiend under global scope
a == null // ReferenceError
typeof a // 'undefined'

Spread Operator(...)

spread operator works for objects!

const point2D = {x: 1, y: 2};
const point3D = {...point2D, z: 3};

let obj = {a: 'b', c: 'd', e: 'f'};
let {a, ...other} = obj;
console.log(a); //b
console.log(other); //{c: "d", e: "f"}

Reference

Notice

  • If you want to follow the latest news/articles for the series of reading notes, Please 「Watch」to Subscribe.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值