天天看點

一,用好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裡有一個數組合并去重方法