gpt4 book ai didi

javascript - 使用 indexOf 在两个数组中查找匹配项

转载 作者:行者123 更新时间:2023-11-29 10:32:41 24 4
gpt4 key购买 nike

我正在接受 FreeCodeCamp Mutations 挑战。这是我必须做的:

Return true if the string in the first element of the array contains all of the letters of the string in the second element of the array.

For example, ["hello", "Hello"], should return true because all of the letters in the second string are present in the first, ignoring case.

The arguments ["hello", "hey"] should return false because the string "hello" does not contain a "y".

Lastly, ["Alien", "line"], should return true because all of the letters in "line" are present in "Alien".

这是我的解决方案。不幸的是它不起作用,尽管我认为可以像这样解决问题。我的错误在哪里?

这是带有我的详细注释的代码:

function mutation(arr) {

//indexOf is case sensitive, so first we make all the elements in the array lowerCase. After that we use the lowerCaseArray instead of our original array

var y = arr.join(" ");
var x = y.toLowerCase();
var lowerCaseArray = x.split(" ")

// This variable will contain the number of matches

var matchCounter = 0;

//The for loop picks a letter from the second element
//(lowerCaseArray[1][i]) of an array and then we look
//if a match in the first element of an array(lowerCaseArray[0] is found).
//If there is a match, then the indexOf would return a number >=0.
//In this case we add 1 to our matchCounter.

for (i = 0; i < lowerCaseArray[1].length; i++) {
if(lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) > 0) {
matchCounter+= 1;

}

//Finally we compare the matchCounter length with the second
//element of our array. If matchCounter >= the length of our
//array, it means every letter in the second element was found
//within the first element

}
return matchCounter >= arr[1].length;

}

mutation(["floor", "for"]);

出于某种原因,return lowerCaseArray[1][i]; 返回“o”,尽管第二个元素的最后一个字母是“r”。在给定的示例中,matchCount 等于 2,但它应该是 3,因为有 3 个匹配项。也许这是有错误的部分。

最佳答案

您需要检查不相等的 -1,因为零 0 是字符串的有效索引。

if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) !== -1) {
// ^^^^^^

function mutation(arr) {
var y = arr.join(" "),
x = y.toLowerCase(),
lowerCaseArray = x.split(" "),
matchCounter = 0,
i;

for (i = 0; i < lowerCaseArray[1].length; i++) {
if (lowerCaseArray[0].indexOf(lowerCaseArray[1][i]) !== -1) {
matchCounter += 1;
}
}
return matchCounter >= arr[1].length;
}

console.log(mutation(["floor", "for"]));

关于javascript - 使用 indexOf 在两个数组中查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42437166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com