FlatMap
FlatMap本质上将 map 和 filter 数组方法的技术结合在一起(非语法糖)。强烈建议使用 flatMap() 而不是 filter() 和 map() 的组合。
差别:FlatMap只需一次遍历,不会产生中间数组,但
filter()和map()组合会产生中间数组
MDN:developer.mozilla.org/zh-CN/docs/…
flatMap() 方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。它等价于在调用 map() 方法后再调用深度为 1 的 flat() 方法(arr.map(...args).flat()),但比分别调用这两个方法稍微更高效一些。
URL拼接方法
对比下这两种方式
asyncfunction getUrl(userId, limit, category){
return`https://fakestoreapi.com/products${category ? `/category/${category}` : ""}${limit ? Number(limit):""}${userId? Number(userId):""}`;
}
推荐
function constructURL(category, limit, userId) {
const baseURL = "https://fakestoreapi.com/products";
const url = new URL(baseURL);
const params = new URLSearchParams();
if (category) url.pathname += `/category/${category}`;
if (limit) params.append('limit', Number(limit).toString());
if (userId) params.append('userId', Number(userId).toString());
url.search = params.toString();
return url.toString();
}