美文网首页
去掉JS代碼中的for循环

去掉JS代碼中的for循环

作者: 六月繁花开 | 来源:发表于2018-08-31 15:01 被阅读13次

for的弊端:for 循环易读性差,

for循环的优點for 循环性能最好。

1.过滤数组数据中的一些不需要的值(返回對象)

        如 将数组中的 falsy 值去除

        const arrContainsEmptyVal = [3, 4, 5, 2, 3, undefined, null, 0, ""];

        const compact = arr=> arr.filter(Boolean);(返回新的對象)

2.对数组中的数据进行数据处理(返回對象)

    将数组中的 VIP 用户余额加 10

    constusers = [  {username:"Kelly",isVIP:true,balance:20},  {username:"Tom",isVIP:false,balance:19},          {username:"Stephanie",isVIP:true,balance:30}];

     users.map(

      user=> (user.isVIP ? { ...user, balance: user.balance + 10 } : user)

        );

3. 判断字符串中是否含有元音字母(返回boolean)

    const randomStr = "hdjrwqpi";

    constisVowel =char=>["a","e","o","i","u"].includes(char);constcontainsVowel =str=>[...str].some(isVowel);containsVowel(randomStr);

4.判断用户是否全部是成年人(返回boolean)

    constusers = [ {name:"Jim",age:23}, {name:"Lily",age:17}, {name:"Will",age:25}];复制代码

     users.every(user=>user.age >=18);

5.去重

    const dupArr = [1, 2, 3, 3, 3, 3, 6, 7];

    const uniq = arr=> [...new Set(arr)];

    uniq(dupArr);

相关文章

网友评论

      本文标题:去掉JS代碼中的for循环

      本文链接:https://www.haomeiwen.com/subject/qkmswftx.html