在review jsQ1~Q5時,學長姐很推薦我去研究一下reduce語法,聽說非常之好用,第一次去查時,覺得有點複雜...所以默默地先略過,今天重新跟著Akshay學,順便寫一下他交代的回家作業
const arr = [3, 5, 8, 12, 7]
//sum
//basic coding
let sum = 0
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i]
}
console.log(sum); //35
//use reduce()
const output = arr.reduce(function (acc, curr) {
acc = acc + curr
return acc
}, 0)
console.log(output); //35
const arr = [3, 5, 8, 12, 7]
//max
//basic coding
let max = 0
for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i]
}
}
console.log(max); //12
//use reduce()
const getMax = arr.reduce(function (max, curr) {
if (max < curr) {
max = curr
}
return max
}
, 0)
console.log(getMax); //12
const customerList = [
{ firstname: 'emily', age: 28, gentle: 'female', surname: 'kuo' },
{ firstname: 'cash', age: 28, gentle: 'male', surname: 'wang' },
{ firstname: 'miya', age: 35, gentle: 'female', surname: 'wang' },
{ firstname: 'sylar', age: 37, gentle: 'male', surname: 'yang' },
]
const numberByGentle = customerList.reduce(function (acc, curr) {
if (acc[curr.gentle]) {
acc[curr.gentle] = ++acc[curr.gentle]
} else {
acc[curr.gentle] = 1
}
return acc
}, {})
console.log(numberByGentle); // { female: 2, male: 2 }
const numberBySurname = customerList.reduce(function (acc, curr) {
if (acc[curr.surname]) {
acc[curr.surname] = ++acc[curr.surname]
} else {
acc[curr.surname] = 1
}
return acc
}, {})
console.log(numberBySurname); // { kuo: 1, wang: 2, yang: 1 }
const customerBy30Up = customerList.reduce(function (acc, curr) {
if (curr.age > 30) {
acc.push(curr.firstname)
}
return acc
}, [])
console.log(customerBy30Up); //['miya', 'sylar']
看完影片突然覺得reduce好像蠻簡單的耶XD你想對陣列做什麼事都可以,只要把它寫在reduce後面的函式內,acc就是你要的結果,如果你想要得到物件,起始值就先放空物件,想得到陣列,起始值就先放空陣列,想想好像真的什麼事都可以做,難怪學長姐說它很強大。
努力看完天書後,來點輕鬆的吧!分享我兒子的童言童語,調劑身心一下
2021/03/13
剛剛大家聊食物,
阿咖很自豪地插話:我有吃過嘎拎ㄙㄨㄣˋ(加冷筍)喔⋯
大家瞬間愣住⋯
2020/12/25
今早看公車導覽書,
看到關子嶺的水火同源,
咖咖:為什麼會這樣啦?
我努力解釋很久後⋯
我:下次再帶你去看好嗎?
咖:好,我帶消防車去把它滅掉好嗎?