我正在写一个函数,我输入一个字符串,函数检查它在数组中的位置。我已经写了代码,但我一直收到错误,控制台说“内容[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'))
答案 0 :(得分:0)
根据您的评论,您一定要使用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'));

注意:感谢@Andreas& @Keith的评论
修改:添加了可运行的代码段