Javascript TypeError:undefined不是对象-使用forEach计算数组时
我正在做一个搜索栏,我有一个奇怪的错误,这个错误还没有被其他许多相同错误的帖子解决。我有一个数组,我使用Javascript TypeError:undefined不是对象-使用forEach计算数组时,javascript,jquery,foreach,Javascript,Jquery,Foreach,我正在做一个搜索栏,我有一个奇怪的错误,这个错误还没有被其他许多相同错误的帖子解决。我有一个数组,我使用forEach登录到控制台,具体取决于数组的索引。但是,我遇到了以下错误: TypeError: undefined is not an object (evaluating 'sites[index].indexOf') 我的代码如下: var sites = ["Website 1", "Website 2", "Youtube Test Page", "Go to google", "
forEach
登录到控制台,具体取决于数组的索引。但是,我遇到了以下错误:
TypeError: undefined is not an object (evaluating 'sites[index].indexOf')
我的代码如下:
var sites = ["Website 1", "Website 2", "Youtube Test Page", "Go to google", "testing for foreward slashes", "MORE!!! :)", "beachballs", "test2", "Good Luck"];
function search() {
var input = $("#searchBar")[0].value;
sites.forEach(function(index) {
console.log(input);
if (sites[index].indexOf(input) != -1) {
console.log("yay");
}
})
}
这是我的搜索栏:
<input type="text" placeholder="Search the web" id="searchBar" onkeyup="search()"/>
我已经做了很多研究,但都没有结果,所以我非常感谢您的帮助。站点
是一个数组,而不是jQuery集合,因此当您对其调用forEach
时,回调的第一个参数是正在迭代的项,而不是索引。改为:
sites.forEach(function(site) {
console.log(site);
if (site.indexOf(input) != -1) {
console.log("yay");
}
})
Array.forEach回调有3个参数
使用三个参数调用回调:
元素值
元素索引
正在遍历的数组
对于您的情况,您只需要第一个参数currentValue
阅读更多内容使用函数(值、索引)
代替函数(索引)
,您的索引
值将与预期值一致
var sites = ["Website 1", "Website 2", "Youtube Test Page", "Go to google", "testing for foreward slashes", "MORE!!! :)", "beachballs", "test2", "Good Luck"];
function search() {
var input = $("#searchBar")[0].value;
sites.forEach(function(value,index) {
console.log(input);
if (sites[index].indexOf(input) != -1) {
console.log("yay");
}
})
}
arr.forEach(function callback(currentValue[, index[, array]]) {
//your iterator
});