0%

JavaScript 中实用的 API

JavaScript 中实用的 API

1. URL查询参数解析

过去,要从一个URL中获取查询参数(如 id),我们通常需要使用正则表达式或一连串的 split 方法,代码冗长且容易出错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 以前的方式
function getQueryParam(url, param) {
 const search = url.split('?')[1];
 if (!search) { return null; }
 const params = search.split('&');
 for (let i = 0; i < params.length; i++) {
    const pair = params[i].split('=');
    if (pair[0] === param) { return decodeURIComponent(pair[1]); }
  }
 return null;
}

const url = 'https://example.com/page?id=123&category=tech';
const id = getQueryParam(url, 'id'); // "123"

现在,URLSearchParams 对象让这一切变得无比简单:

1
2
3
//现代的方式
const url = new URL('https://example.com/page?id=123&category=tech');
const id = url.searchParams.get('id'); // "123"

内置的 URLSearchParams 不仅代码更短,而且在处理URL编码、多个同名参数等边缘情况时更加健壮可靠。

2. 对象深拷贝

深拷贝是面试和工作中的常见痛点,最广为人知但有缺陷的方法是 JSON.parse(JSON.stringify(obj)),它无法处理 Date 对象、undefined、等特殊类型。

1
2
3
4
5
6
7
8
9
10
const original = {
  birth: new Date('1990-01-01'),
  id: undefined,
};

// 以前的方式
const copy = JSON.parse(JSON.stringify(original));
// 问题暴露
console.log(copy.birth); // "1990-01-01T00:00:00.000Z" (变成了字符串)
console.log(copy.id);    // undefined (undefined 丢失)

现在,我们有了原生的、强大的深拷贝工具 structuredClone

1
2
3
4
5
// 现代的方式
const copy = structuredClone(original);
// 完美拷贝
console.log(copy.birth);// Date object(依然是 Date 对象)
console.log(original.birth === copy.birth); // false(是全新的对象)

structuredClone 是官方推荐的深拷贝方式,支持绝大多数数据类型(除函数、DOM节点等),彻底解决了 JSON 方法的弊端。

3. 数组分组

1
2
3
4
5
6
7
8
9
10
11
12
13
const products = [
  { name'苹果'category'水果' },
  { name'电视'category'电器' }
];

// 以前的方式
const grouped = products.reduce((acc, product) => {
 const key = product.category;
 if (!acc[key]) { acc[key] = []; }
  acc[key].push(product);
 return acc;
}, {});
// grouped: { '水果': [...], '电器': [...] }

ES2023 引入了 Object.groupBy(),让分组操作变得语义化且极其简单。

1
2
3
// 现代的方式
const grouped = Object.groupBy(products, product => product.category);
// grouped: { '水果': [...], '电器': [...]}

Object.groupBy() 将一个意图直接翻译成了一行代码,可读性远超复杂的 reduce 实现。