javascript - 查找子字符串时无法返回数组的长度

标签 javascript arrays

当满足子字符串条件时,如何返回数组的长度?我有三个数组:

arr1 = ["V1","V1","V1","V1","V1","V2","V2","V2"...]
arr2 = ["A1","A1","B1","B1","B1","A2","A2","A2"...]
arr3 = ["V1A1*","V1A1*","V1B1*","V1B1*"...]

如何返回过滤后的 arr3 的长度,其中 arr1[i]+arr2[i] 是该元素的子字符串? (“V1A1”)

第一次迭代的预期输出为 2。 (i=0)

提前致谢!

最佳答案

看起来你是说这三个数组的长度相同,并且对于每个索引 i数组中,您想知道是否 arr1[i] + arr2[i]arr3[i] 的子串。然后,您想知道有多少元素满足此条件。

要实现此目的,您需要查看数组的索引并使用 string.indexOf方法来查看是否满足您的条件。

var length = arr1.length,
    matchCount = 0,
    isMatch, i;

for(i = 0; i < length; i += 1) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf
    // indexOf returns the array index where the substring is found, or -1 if it is not found
    isMatch = arr3[i].indexOf(arr1[i] + arr2[i]) > -1;
    if (isMatch) {
        matchCount += 1;
    }
}

console.log(matchCount);

关于javascript - 查找子字符串时无法返回数组的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54713940/

相关文章:

C 数组,向右移动元素未按预期工作

javascript - If 语句检查某个值是否在数组或值范围内

javascript - 尝试使用 Javascript 输出到文本框

javascript - jQuery/CSS 不同颜色的半圆进度条

javascript - HTML:输入类型日期和月份范围

javascript - 我怎样才能以 <a href="开始并在此处有一个数组元素然后以 </a> 结束?

javascript - 如何刷新模板中存在的指令并且指令具有自己的数据范围

python numpy : loading files to list, 并转换为数组,但错误 "array is too big."

javascript改变数组中的元素

arrays - 如何在 VB.NET 中声明内联数组