代码之家  ›  专栏  ›  技术社区  ›  Jack Bashford

TypeError:undefined不是对象-使用forEach计算数组时

  •  -2
  • Jack Bashford  · 技术社区  · 6 年前

    我正在做一个搜索栏,我有一个奇怪的错误,并没有被解决的许多其他职位的相同错误。我有一个数组,我正在使用 forEach index 数组的。但是,我得到了这个错误:

    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()"/>
    

    我做了很多研究都没有用,所以我很感激你的帮助。

    3 回复  |  直到 6 年前
        1
  •  6
  •   CertainPerformance    6 年前

    sites 是一个 数组 forEach 在它上面,回调的第一个参数是

    sites.forEach(function(site) {
        console.log(site);
        if (site.indexOf(input) != -1) {
            console.log("yay");
        }
    })
    
        2
  •  1
  •   anshuVersatile    6 年前
    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");
            }
        })
    }
    
        3
  •  1
  •   Community Egal    4 年前

    回调由三个参数调用:

    这个

    元素索引

    正在遍历的数组

    arr.forEach(function callback(currentValue[, index[, array]]) {
        //your iterator
    });
    

    至于你的情况,你只需要第一个参数 currentValue

    阅读更多 Array.prototype.forEach() - Javascript | MDN