本文介绍了过滤以JavaScript中的字母开头的列表元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将以'N'开头的列表元素整理成新列表。
为什么这不起作用?

I am trying to sort out list elements that starts with 'N' into a new list.Why won't this work?

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

function firstN(){
  for (let i=0;i<countries.length;i++){
    countries[i].startsWith("N")
    }
}

let startsWithN = countries.filter(firstN())


推荐答案

这与@ adeneo的回答大致相同,只是一点点:

This is roughly the same as @adeneo's answer, just a little terser:

const countries = ['Norway', 'Sweden',  'Denmark', 'New Zealand'];

const startsWithN = countries.filter((country) => country.startsWith("N"));

console.log(startsWithN);

// Output: [ 'Norway', 'New Zealand' ]

这篇关于过滤以JavaScript中的字母开头的列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 10:00