flatMap()
数组的一个api,数组的每一项执行callback,返回一个新的数组; 也会打平深度为1的子项,比使用map + flat的组合性能更好;
const number = [1,2,3,4,5];
number.flatMap((number) => {
return number %2 === 0? [number*number] : []
})
链式调用数组api调整顺序
number.sort((a,b) => a-b).filter((n) => n%2 !==0).map((n) => n *3)
当链式使用数组api,处理数据时,将sort,api后移,减少sort需要处理的数据项,将提供处理能力;
合理使用reduce
在处理请求回来的数据,将array转换成map时,合理使用reduce,使得数据的可读性更好
fetch("https://jsonplaceholder.typicode.com/todos/")
.then(res=>res.json())
.then(todos=>{
// using Map
const todosForUserMap = {};
todos.forEach(todo=>{
if (todosForUserMap[todo.userId]){
todosForUserMap[todo.userId].push(todo);
}else{
todosForUserMap[todo.userId] = [todo];
}
})
console.log(todosForUserMap)
})
// 优化成reduce后;
fetch('https://xxxx')
.then(res => res.json()))
.then(todos => {
const todoMap = todos.reduce((accumulator, todo) => {
if(accumulator[todo.userId]) accumulator[todo.userId].push(todo);
if(!accumulator[todo.userId]) accumulator[todo.userId] = [todo]
return accumulator;
}, {})
})
充分使用js class 原生api
为了提高代码可读性和可扩展性,如果是js 原生有支持的一些class,可以优先使用;比如url的处理,可以优先使用相关class类来进行处理
async function 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());
url.search = params.toString();
return url.toString()
}