如何使用 .match javascript 方法来搜索数组而不是字符串?

How do I use the .match javascript method to search an array versus a string?

这是使用 .match 方法搜索字符串然后 return 是否找到匹配项的简单方法。

    var match = "hello joe, how are you?".match('joe');

    if (match) {
      console.log(match[0]);
    } else {
      console.log('no match found : (');
    }

当尝试使用 .match 方法在数组中搜索特定字符串时 – 我无法获得 return。有什么建议吗?

var array = ['charlie','jeff','joe'].match('jeff');

if (array) {
  console.log(array[0]);
} else {
  console.log('no dice');
}

.match() is a JavaScript string method, not array. In your example, you want to use the array .indexOf() 方法。它 returns 数组中特定项目的索引(位置),然后您可以使用它来获取该项目。我建议阅读文档(上面链接的 MDN)以获取更多使用信息。

var array = ['charlie','jeff','joe'];

if (array.indexOf('jeff') > -1) {
  console.log(array[array.indexOf('jeff')]);
} else {
  console.log('no dice');
}