当满足子字符串条件时,如何返回数组的长度?我有三个数组:
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/