Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript TypeError:undefined不是对象-使用forEach计算数组时_Javascript_Jquery_Foreach - Fatal编程技术网

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
});