3 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超6個(gè)贊
您在這里面臨的主要問題是,您無法在迭代列表時(shí)創(chuàng)建新的人群,并且被迫對新變量進(jìn)行硬編碼,例如const age3040 = []. 通常,您會(huì)使用一個(gè)對象來實(shí)現(xiàn)這一點(diǎn),這樣您就可以最終得到一個(gè)這樣的對象。
const ranked = {
"20": ["Helia"],
"30": ["Bill", "Jon"],
// and so on
}
您可能會(huì)認(rèn)為這是一個(gè)計(jì)數(shù)問題。在這種情況下,剩下要做的唯一一件事就是在計(jì)算出您需要什么后弄清楚人們屬于哪個(gè)類別。
const ranked = {}
for (const [name, age] of mainArr) {
// a function that decides what key to give the person in that age bracket
const tier = decideTier(age)
const people = ranked[tier]
if (!people) {
// if a previous person with this age has not been seen before you'll
// have to create a new array with the person in it so that you can
// push new names in it the next time
ranked[tier] = [name]
} else {
people.push(name)
}
}
console.log(ranked["20"])
你在這里尋找的東西的一個(gè)例子叫做groupBybtw 并且可以在像Ramda這樣的庫中找到。

TA貢獻(xiàn)1995條經(jīng)驗(yàn) 獲得超2個(gè)贊
您的代碼中存在三個(gè)問題
ageCheck
根本沒有使用||
應(yīng)該&&
函數(shù)
checkAge
沒有被調(diào)用所以你不會(huì)得到結(jié)果
給你舉個(gè)例子,希望對你有幫助。
const arr1 = ['Sarah', 37];
const arr2 = ['Mike', 32];
const arr3 = ['Bill', 25];
const arr4 = ['Chris', 24];
const arr5 = ['Joe', 44];
const arr6 = ['Jesse', 33];
const arr7 = ['Jon', 28];
const arr8 = ['Michael', 55];
const arr9 = ['Jill', 59];
const arr10 = ['Helia', 4];
const mainArr = [arr1, arr2, arr3, arr4, arr5, arr6, arr7, arr8, arr9, arr10];
const reuslt = [{
range: '0-20',
names: []
}, {
range: '21-30',
names: []
}, {
range: '31-40',
names: []
}, {
range: '41-50',
names: []
}, {
range: '51-60',
names: []
}];
for (let index = 0; index < mainArr.length; index++) {
const item = mainArr[index];
if (item[1] > 0 && item[1] <= 20) {
reuslt[0].names.push(item[0]);
} else if (item[1] <= 30) {
reuslt[1].names.push(item[0]);
} else if (item[1] <= 40) {
reuslt[2].names.push(item[0]);
} else if (item[1] <= 50) {
reuslt[3].names.push(item[0]);
} else if (item[1] <= 60) {
reuslt[4].names.push(item[0]);
}
}
console.log(reuslt);

TA貢獻(xiàn)1770條經(jīng)驗(yàn) 獲得超3個(gè)贊
使用 a if else if,你應(yīng)該使用&¬||
像這樣:
let age020 = []
let age2030 = []
let age3040 = []
let age4050 = []
let age5060 = []
mainArr.forEach(arr =>{
const age = arr[1]
if(age >= 0 && age <= 20){
age020.push(arr)
}else if(age >= 30 && age <= 40){
age3040.push(arr)
}
//... do same to other age range
})
console.log(age020)
console.log(age3040)
添加回答
舉報(bào)