JavaScript 函数参数传递数组

JavaScript function parameter passing array

本文关键字:数组 参数传递 函数 JavaScript      更新时间:2023-09-26

我正在尝试将数组传递到一个函数中,该函数查看当前URL的一部分,然后根据该URL过滤页面上的数据。该数组具有用户可以在页面上搜索的许多值。

目前 filterFor param 只能接受一个字符串,我希望它接受一个可以搜索的字符串数组。

function queryList(filterFor, filterClass, filterClassTwo) {
    var searchResult = $.urlParam('filter');
    if (searchResult === filterFor) {
        degreeProgram.filter(function (item) {
            if (item.values()[filterClass] === filterFor || 
                item.values()[filterClassTwo] === filterFor) {
                return true;
            } else {
                return false;
            }
        });
        $('#filterDisplay').html('<span>' + filterFor + '</span>');
        $('#filterDisplay').addClass('activated');   
    }   
}
queryList('Chemistry', 'programName');

这将允许页面过滤以显示任何具有化学值的程序名称。该函数查看的 URL 部分如下所示:

?filter=Chemistry

我需要它像这样工作:

var myArray = ['Chemistry', 'Math' 'Earth Science'];
queryList(myArray, 'programName');

允许我传入查询可以接收的程序列表。

您应该能够使用内置数组方法完成此操作。 indexOf() 用于确定数组是否包含搜索词。

function arrayExample(myArray){
  var searchTerm = "testing";
  if(myArray.indexOf(searchTerm) !== -1){
     alert("match");
  }
  else{
     alert("no match");
  }
}
arrayExample("blah","aaa","oooh");
arrayExample("testing","aaa","oooh");