我正在通过FreeCodeCamp突变挑战。这是我必须做的:查找两个数组中的索引匹配
返回真,如果在数组的第一个元素的字符串包含 所有的数组的第二个元素串的字母。
例如,[“hello”,“Hello”]应该返回true,因为第二个字符串中的所有 字母都出现在第一个忽略大小写中。
参数[“hello”,“hey”]应返回false,因为字符串 “hello”不包含“y”。
最后,[“Alien”,“line”]应该返回true,因为“line”中的所有 字母都出现在“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个匹配。也许这是一个错误的部分。
我运行了你的代码,它正确地遍历所有3个字母,'f','o'和'r'。你能再次运行并验证吗? –
它的确如此,但它返回false,因为matchCounter等于2,而不是3。 –