【问题标题】:How do I match string with the array of strings如何将字符串与字符串数组匹配
【发布时间】:2021-04-28 22:52:33
【问题描述】:

我有一个字符串数组:

todo=[

'Get up',
'Brush my teeth',
'Go to work',
'play Games'
];

我正在尝试将其与此匹配:

模板:

<input (input)="checkArrays($event)" />

在我的 Component.ts 中,我使用的功能是:

checkArrays(e){
let query=e.target.value;
console.log(query);

let todoResult = this.todo.findIndex((item) => { return item.startsWith(query);})
let doneResult = this.done.findIndex((item) => { return item.startsWith(query);})
if(doneResult!=-1){
  console.log('found in Tasks (done)'+doneResult)
}if(todoResult!=-1){
  console.log('found in Tasks (todo)'+todoResult)
}

它的作用是,当我开始输入“G”时,它匹配数组中的第一个项目,即“起床”,而不匹配“开始工作”。当我输入“Go”时,它与“Go to work”匹配。我想要的功能基本上是当我开始输入“G”时它应该给我“起床”和“去上班”。某种子字符串之类的功能。

【问题讨论】:

  • findIndex()方法返回数组中第一个满足条件的元素的索引,需要使用filter代替。

标签: javascript angular web


【解决方案1】:

findIndex()方法返回数组中第一个满足条件的元素的索引,需要用filter代替。

todo=[
'Get up',
'Brush my teeth',
'Go to work',
'play Games'
];


console.log(todo.filter(item => item.startsWith("G")));

// or 

// Better one is using regex -->
console.log(todo.filter(item => /^g/gi.test(item))); // for case-insensitive search

【讨论】:

  • 感谢您的回答。接下来我需要实现不区分大小写的搜索。你为我节省了很多时间。
【解决方案2】:

您应该使用filter() 而不是findIndex()。所以它可以是:

checkArrays(e) {
  const query = e.target.value;
  
  const todoResult = this.todo.filter(item => item.startsWith(query));
  const doneResult = this.done.filter(item => item.startsWith(query));
  
  if (doneResult.length > 0) {
    console.log(`found in Tasks (done) ${doneResult}`)
  }
  if (todoResult.length > 0) {
    console.log(`found in Tasks (todo) ${todoResult}`)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-18
    • 2014-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    相关资源
    最近更新 更多