【问题标题】:Make a new array using regex to find elements starting with A through J使用正则表达式创建一个新数组以查找以 A 到 J 开头的元素
【发布时间】:2020-04-10 04:17:03
【问题描述】:
let cityList = ['Clevelend', 'Birmingham', 'Austin', 'Milwaukee'];

citiesAtoJ = arr => {
    console.log(arr.map( () => { /\b[A-J].*?/g} ));
};

citiesAtoJ(cityList);

我知道我需要使用带有 map 的函数,但我有点迷路了。

【问题讨论】:

    标签: javascript arrays regex dictionary arrow-functions


    【解决方案1】:

    .map 将构造一个新数组,其元素数量与旧数组相同 - 但您只想包含通过测试的元素。请改用.filter

    let cityList = ['Clevelend', 'Birmingham', 'Austin', 'Milwaukee'];
    
    const citiesAtoJ = arr => arr.filter(
      city => /\b[A-J]/.test(city)
    );
    
    console.log(citiesAtoJ(cityList));

    【讨论】:

      猜你喜欢
      • 2014-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多