Uncaught TypeError:undefined不是var new_arr=filtered.split(

Uncaught TypeError: undefined is not a function on line var new_arr = filtered.split(',');

本文关键字:filtered split arr TypeError undefined 不是 new var Uncaught      更新时间:2023-09-26

我写了一点javascript,但我遇到了错误,通常不会发生,但我仍然不知道我做错了什么,这是我的代码`

var stu = ['ron','john','johnny','roni','rob','bob'];
        $('#studentName').keyup(function(){
            var student = $('#studentName').val();
            alert(findStu(student));
        });
        function findStu(val){
            var filtered = stu.filter(function(str){
                return str.indexOf(val) != -1;
            });
            var new_arr = filtered.split(',');
            var html = "";
            new_arr.foreach(function(element,index,array){
                console.log('a['+index+']='+element);
            });
        }

`

我想做的是,当有人键入r时,我的代码应该返回"ron,roni,rob"之类的自动建议,但我在var new_arr = filtered.split(',') '' undefined is not a function 行遇到错误

如果您正在查找"ron,roni,rob"中的推荐字符串结果,请检查以下代码:

var stu = ['ron','john','johnny','roni','rob','bob'];
    $('#studentName').keyup(function(){
        var student = $('#studentName').val();
        alert(findStu(student));
    });
    function findStu(val){
        //Filters list of students and then create a string of its elements
        var filtered = stu.filter(function(str){
            return str.indexOf(val) != -1;
        }).join();
        var html = "";
        new_arr.foreach(function(element,index,array){
            console.log('a['+index+']='+element);
        });
    }

解释:

.filter()函数将根据您的条件返回一个已筛选元素的数组。此处的文档

CCD_ 4随后将加入该阵列的片段。此处的文档