假设我有一个数组常量,如下所示:
const people = [
{ first: 'John', last: 'Doe', year: 1991, month: 6 },
{ first: 'Jane', last: 'Doe', year: 1990, month: 9 },
{ first: 'Jahn', last: 'Deo', year: 1986, month: 1 },
{ first: 'Jone', last: 'Deo', year: 1992, month: 11 },
{ first: 'Jhan', last: 'Doe', year: 1989, month: 4 },
{ first: 'Jeon', last: 'Doe', year: 1992, month: 2 },
{ first: 'Janh', last: 'Edo', year: 1984, month: 7 },
{ first: 'Jean', last: 'Edo', year: 1981, month: 8},
];
我想回报80年代出生的每个人的价值。
我当前实现此目的的功能是:
const eighty = people.filter(person=> {
if (person.year >= 1980 && person.year <= 1989) {
return true;
}
});
我的问题:是否可以将startsWith()和filter()一起使用来替换:
if (person.year >= 1980 && person.year <= 1989) {
return true;
}
用
startsWith('198')
代替?如果是,那么正确的方法是什么?
最佳答案
你可以做
people.filter(person => String(person.year).startsWith('198'))
const people = [
{ first: 'John', last: 'Doe', year: 1991, month: 6 },
{ first: 'Jane', last: 'Doe', year: 1990, month: 9 },
{ first: 'Jahn', last: 'Deo', year: 1986, month: 1 },
{ first: 'Jone', last: 'Deo', year: 1992, month: 11 },
{ first: 'Jhan', last: 'Doe', year: 1989, month: 4 },
{ first: 'Jeon', last: 'Doe', year: 1992, month: 2 },
{ first: 'Janh', last: 'Edo', year: 1984, month: 7 },
{ first: 'Jean', last: 'Edo', year: 1981, month: 8},
];
var filtered = people.filter(p => String(p.year).startsWith('198'));
console.log(filtered);
关于javascript - 组合filter()和startsWith()以过滤数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50030338/