Javascript 组合filter()和startsWith()以筛选数组
假设我有一个数组常量,如下所示:Javascript 组合filter()和startsWith()以筛选数组,javascript,ecmascript-6,Javascript,Ecmascript 6,假设我有一个数组常量,如下所示: 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',
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;
}
});
我的问题:是否可以与一起使用以替换:
if (person.year >= 1980 && person.year <= 1989) {
return true;
}
用“198”来代替Starts
如果是,正确的方法是什么?您可以这样做
people.filter(person => String(person.year).startsWith('198'))
康斯特人=[
{第一个:'约翰',最后一个:'多伊',年份:1991,月份:6},
{第一个:'简',最后一个:'多伊',年份:1990,月份:9},
{第一个:'Jahn',最后一个:'Deo',年份:1986,月份:1},
{第一个:'Jone',最后一个:'Deo',年份:1992,月份:11},
{第一个:'Jhan',最后一个:'Doe',年份:1989,月份:4},
{第一个:'Jeon',最后一个:'Doe',年份:1992,月份:2},
{第一个:“Janh”,最后一个:“Edo”,年份:1984,月份:7},
{第一个:“吉恩”,最后一个:“江户”,年份:1981,月份:8},
];
var filtered=people.filterpr=>Stringp.year.startsWith'198';
console.logfiltered 抱歉,这并不是您所要求的,但是如果您对在一个操作中解决问题感兴趣,而不是专门使用startsWith,那么您可以用数字来完成它 Math.floorperson.year/10==198 由于没有字符串转换,它的效率可能会稍高一些,并且不会出现其他字符串以相同方式开始匹配的问题。是的,您可以:
people.filter(person => String(person.year).startsWith('198'));
然而,你可能不想这样做,因为你可能会遇到一些奇怪的事情,比如年份是19812,而年份是无效的
相反,您最好使用正则表达式:
people.filter(person => /^198\d$/.test(person.year));
这将只与20世纪80年代的年份相匹配。您也不必进行额外的强制转换,因此它也有点干净。您必须先将其转换为字符串…但它也将覆盖19801年,例如,这是无效的,而不是StartWith,您可以通过匹配正则表达式来避免提到的边缘情况。也许/^198\d$/.testStringYear您不需要这个if语句。只需返回条件:people.filterperson=>person.year>=1980&&person.year>=1980&&year return Math.floorperson.year/10==198我的基本问题是,这些替代解决方案可以为您节省半行代码,作为交换,与简单的值检查相比,转换为字符串+检查子字符串会带来巨大的开销,或者在Math.floor的情况下,读取起来非常不直观。我建议您按照@Xufox的建议,只返回布尔表达式,而不是使用if分支。这将有助于避免边缘大小写大于1989。+1这肯定更可靠、更直观,我认为在使用过滤数组@brabster时,我肯定会使用它,但是Zohaib的回答告诉了我一种将这两种方法结合起来的方法,正如我最初想知道的那样,所以我给他打勾人。干杯。好朋友乐意帮忙;是p=>Stringp.year还是p=>Stringpeople.year?很抱歉犯了这个错误。。。p、 年或人。年无论你在用什么+1谢谢@samanime!将使用Math.floor或regex而不是startsWith筛选编号数组。