es6方法使用技巧目录map

**

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"}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值