【问题标题】:find specific string in array index and get matching values在数组索引中查找特定字符串并获取匹配值
【发布时间】:2019-10-27 10:52:07
【问题描述】:

我正在尝试从一个数组中获取索引,其中 'Type_' 从数组中匹配。

数组是这样的:

['Type_test', 'Type_hello', 'Type_google', 'Type_apple', 'mango', 'orange'];

答案应该是这样的:

['Type_test', 'Type_hello', 'Type_google', 'Type_apple'];

【问题讨论】:

标签: javascript json object


【解决方案1】:

试试这个:

const array = ['Type_test', 'Type_hello', 'Type_google', 'Type_apple', 'mango', 'orange'];
const result = array.filter(e => e.startsWith('Type_'));
console.log(result);

filter 函数接受一个谓词函数并返回一个新数组,其中仅包含满足谓词的项。如果函数返回一个真值,则该元素将被保留,反之亦然。对于数组中的每个元素,将使用当前元素、当前元素的索引和数组调用谓词函数。

此代码检索array 中以Type_ 开头的元素。换句话说,它过滤数组,使每个元素e 满足条件e.startsWith('Type_')

【讨论】:

  • filter() 不是 ES6 特性,只有箭头函数用法是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多