一,用好filter,map,和其他高阶便利函数

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

const compact = arr => arr.filter(Boolean);

 

// console.log(compact(arrContainsEmptyVal))

 

//问题二: 将数组中的 VIP 用户余额加 10

const users = [

{ username: "Kelly", isVIP: true, balance: 20 },

{ username: "Tom", isVIP: false, balance: 19 },

{ username: "Stephanie", isVIP: true, balance: 30 }

];

var newUsers = users.map( user => (user.isVIP ? user.balance + 10 : user)

)

// console.log(newUsers)

 

//问题三: 判断字符串中是否含有元音字母

const randomStr = "hdjrwqpi";

const isVowel = char => ["a", "e", "o", "i", "u"].includes(char);

const containsVowel = str => [...str].filter(isVowel);

 

// containsVowel(randomStr);

//下面拆解第一个函数

function getIs(isVowe){

return ["a", "e", "o", "i", "u"].includes(isVowe)

}

//第二个

function isContain(str) {

return [...str].some(getIs) //...是一种语法糖,它语序将数组作为函数的参数,而不用allpy

}

// console.log(isContain(randomStr))

 

// console.log(containsVowel(randomStr))

 

// 问题四: 判断用户是否全部是成年人

const userss = [

{ name: "Jim", age: 23 },

{ name: "Lily", age: 17 },

{ name: "Will", age: 25 }

];

const adults = userss.filter( user => user.age > 18)

// console.log(adults)

 

// 问题五: 找出上面用户中的第一个未成年人


 

// 问题六: 将数组中重复项清除

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

 

const single = arr => [...new Set(arr)] // ...在这里是什么意思

// console.log(single(dupArr))

function getSingle(arr){

return [new Set(arr)]

}

console.log(getSingle(dupArr))

 

// 问题七: 生成由随机整数组成的数组,数组长度和元素大小可自定义

const genNumArr = (length, limit) =>

Array.from({ length }, _ => Math.floor(Math.random() * limit));

 

console.log(genNumArr(5, 100))

// Array.from方法,第一个参数为要放入的数组或者对象

//在MDN里有一个数组合并去重方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值