看完本文,希望可以写出更加漂亮、简洁、函数式的代码🤞
reduce
reduce 可以用来 汇总
数据
const customer = [
{id: 1, count: 2},
{id: 2, count: 89},
{id: 3, count: 1}
];
const totalCount = customer.reduce((total, item) =>
total + item.count,
0 // total 的初始值
);
// now totalCount = 92
把一个对象数组变成一个以数组中各个对象的 id 为属性名,对象本身为属性值的对象。haoduoshipin(http://haoduoshipin.com/videos/240/)
let products = [
{
id: '123',
name: '苹果'
},
{
id: '345',
name: '橘子'
}
];
const productsById = products.reduce(
(obj, product) => {
obj[product.id] = product
return obj
},
{}
);
console.log('result', productsById);
map
map 可以理解为是数组的转换器,依次对数组中的每个元素做变换进而得到一个新的数组。
const integers = [1, 2, 3, 4, 6, 7];
const twoXIntegers = integers.map(i => i*2);
// twoXIntegers are now [2, 4, 6, 8, 12, 14]
// integers数组并不会受到影响
find🔥
筛选出数组中的 个别
元素。
const posts = [
{id: 1, title: 'Title 1'},
{id: 2, title: 'Title 2'},
];
// find the title of post whose id is 1
const title = posts.find(p => p.id === 1).title;
唉~ 使用了半年的 es6才发现有这么好用的东西,译者傻缺还像下面这么写过呢。
const posts = [
{id: 1, title: 'Title 1'},
{id: 2, title: 'Title 2'},
];
const title = posts.filter(item => item.id === 1)[0].title;
filter
筛选出数组中 某些
符合条件的元素组成新的数组。
const integers = [1, 2, 3, 4, 6, 7];
const evenIntegers = integers.filter(i => i/2 === 0);
// evenIntegers are [2, 4, 6]
请大家自行思考下 filter
和 find
的区别
数组concat
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 0];
const arrTarget = [...arr1, ...arr2];
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
对象操作
function operation(query, option = {}) {
const param = {...query, ...option};
// ....
return param;
}
let opt = {startTime: 123455555, endTime: 113345555};
let q = {name: '一步', age: 'xxx'};
operation(q, opt);
// {name: "一步", age: "xxx", startTime: 123455555, endTime: 113345555}
对象是引用传参的,所以函数内部应该尽可能的保证传入的参数不受到污染。
为对象动态地添加字段
const dynamicKey = 'wearsSpectacles'; const user = {name: 'Shivek Khurana'}; const updatedUser = {...user, [dynamicKey]: true}; // updatedUser is {name: 'Shivek Khurana', wearsSpectacles: true}
将对象转换为query字符串👏
const params = {color: 'red', minPrice: 8000, maxPrice: 10000};
const query = '?' + Object.keys(params)
.map(k =>
encodeURIComponent(k) + '='+ encodeURIComponent(params[k])
)
.join('&');
// encodeURIComponent encodes special characters like spaces, hashes
// query is now "color=red&minPrice=8000&maxPrice=10000"
得到对象数组的元素 index
const posts = [ {id: 13, title: 'Title 221'}, {id: 5, title: 'Title 102'}, {id: 131, title: 'Title 18'}, {id: 55, title: 'Title 234'} ]; // to find index of element with id 131 const requiredIndex = posts.map(p => p.id).indexOf(131);
更加优雅的写法呱呱呱提供:
const posts = [
{id: 13, title: 'Title 221'},
{id: 5, title: 'Title 102'},
{id: 131, title: 'Title 18'},
{id: 55, title: 'Title 234'}
];
const index = posts.findIndex(p => p.id === 131)
删除对象的某个字段
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const userWithoutPassword = Object.keys(user)
.filter(key => key !== 'password')
.map(key => {[key]: user[key]})
.reducer((accumulator, current) =>
({...accumulator, ...current}),
{}
)
;
// userWithoutPassword becomes {name: 'Shivek Khurana', age: 23}
这里我认为原作者有点为了函数式编程而函数式了,下面是我的解决方案:
const user = {name: 'Shivek Khurana', age: 23, password: 'SantaCl@use'};
const newUser = {...user};
delete newUser.password;
// {name: "Shivek Khurana", age: 23}
以上代码片段的共同原则:不改变原数据。希望大家的代码都可以尽可能的简洁,可维护🙏。
共有 0 条评论