检查数组是否包含字符串的一部分并找到索引号 [英] Check if an array contains part of a string and find the index number

查看:21
本文介绍了检查数组是否包含字符串的一部分并找到索引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

const myArr = [ "blue", "red", "orange", "green" ];

我想知道如何检查数组是否包含字符串的一部分以及匹配字符串的索引号.

I was wondering how to check if an array contains part of a string and the index number of the matching string.

我在网上看到过,但索引号不显示位置,除非它是数组中的全名.

I’ve seen this online but the index number doesn’t show the position unless it’s the full name in the array.

myArr.indexOf("oran")

推荐答案

您可以使用 some 以检查是否至少有一个元素验证您的条件:

You can use some to check if there's at least one element verifying your condition :

var hasSome = myArr.some(function(v){ return v.indexOf("oran")>=0 })

如果您需要索引,反向 for 循环是更简单的解决方案:

If you need the index, a reverse for loop is the simpler solution :

for (var i=myArr.length; i--;) {
     if (myArr[i].indexOf("oran")>=0) break;
}

循环之后,i-1 如果没有元素匹配,它是它的索引,如果有一个匹配.

After the loop, i is -1 if no element matches, it's its index if one matches.

请注意,在 ES6(JavaScript 的下一个版本)中,您将在数组上使用 findfindIndex 方法以及 includes字符串上的方法,这意味着你可以做

Note that in ES6 (the next version of JavaScript), you'll have the find and findIndex methods on arrays and the includes method on strings, which means you'll be able to do

var i = myArr.findIndex(v => v.includes("oran"));

这篇关于检查数组是否包含字符串的一部分并找到索引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆