**
es6方法使用技巧目录1
**
一、map箭头写法
const useList = listData.map(item => {
return item + 1;
})
因为大括号内有一行语句有return,可以省略{}和return
const useList = listData.map(item => item + 1);
假如返回的值为对象
const listData = [1, 2, 3];
const useList = listData.map(item => {
return { name: item };
});
console.log(useList);
// {name: "a"}
// {name: "b"}
// {name: "c"}
按照简写规则,简写为下面的
const useList = listData.map(item => { name: item } );
但是报错,因为这和简写前的大括号冲突,有歧义。
所以返回的是对象简写需要在大括号前面加小括号
const listData = ['a', 'b', 'c'];
const useList = listData.map(item => ({ name: item }));
console.log(useList);
// {name: "a"}
// {name: "b"}
// {name: "c"}
总结
一、返回值为对象,简写需要在大括号外面加小括号;
二、map,对象里的每项增加新的属性,例如下面的type
const listData = [{ name: 'a' }, { name: 'b' }, { name: 'c' }];
const useList = listData.map(item => ({
...item,
type: item.name === 'a' ? 'sigle' : 'combine',
}));
console.log(useList);
// {name: "a", type: "sigle"}
// {name: "b", type: "combine"}
// {name: "c", type: "combine"}