I am writing a function, where I input a string and the function checks it's position in the array. I have writen the code, but i keep getting an error and the console says "contents[i] not identified" but i already defined the array.
我正在写一个函数,我输入一个字符串,函数检查它在数组中的位置。我写了代码,但我一直收到错误,控制台说“内容[i]未识别”,但我已经定义了数组。
function idxP1(contents,pattern) {
var contents = [ "Loughborough University offers degree programmes and
world class research.", "An alternative University", "Yet another
University"];
return contents.findIndex(word => word.toLowerCase().includes(pattern));
}
alert(idxP1(null, 'Uni'))
1 个解决方案
#1
0
Based on your comments you should definitely use findIndex
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
基于您的评论,您一定要使用findIndex:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
function idxP1(contents, pattern) {
var contents = ["Loughborough University offers degree programmes and world class research.", "An alternative University", "Yet another University"];
return contents.findIndex(word => word.toLowerCase().includes(pattern.toLowerCase()));
}
console.log(idxP1(null, 'Uni'));
Note: Thanks to @Andreas & @Keith for their comments
注意:感谢@Andreas和@Keith的评论
Edit: Added a runnable code snippet
编辑:添加了一个可运行的代码段
#1
0
Based on your comments you should definitely use findIndex
: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
基于您的评论,您一定要使用findIndex:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
function idxP1(contents, pattern) {
var contents = ["Loughborough University offers degree programmes and world class research.", "An alternative University", "Yet another University"];
return contents.findIndex(word => word.toLowerCase().includes(pattern.toLowerCase()));
}
console.log(idxP1(null, 'Uni'));
Note: Thanks to @Andreas & @Keith for their comments
注意:感谢@Andreas和@Keith的评论
Edit: Added a runnable code snippet
编辑:添加了一个可运行的代码段