Jquery 为什么我的inArray测试总是返回false?

Jquery 为什么我的inArray测试总是返回false?,jquery,asp.net,Jquery,Asp.net,为什么无论字符串是否在数组中,inArray测试总是返回false?我从表单中收集内容并连接两个字符串,然后将它们添加到数组中。然后使用inArray检查我添加的字符串是否已经存在。当我运行测试时,我总是出错。我可能做错了什么。这是我的密码 $("#saveBtn").click(function () { for (var x = 0; x < checkedindex.length; x++) { var ind = checked

为什么无论字符串是否在数组中,inArray测试总是返回false?我从表单中收集内容并连接两个字符串,然后将它们添加到数组中。然后使用inArray检查我添加的字符串是否已经存在。当我运行测试时,我总是出错。我可能做错了什么。这是我的密码

   $("#saveBtn").click(function () {


         for (var x = 0; x < checkedindex.length; x++) {
             var ind = checkedindex[x];

             var dateofclass = $(".TextBoxDate:eq(" + ind + ")");
             var timeofclass = $(".TextBoxTime:eq(" + ind + ")");
             var classday = $("select[name='searchString']:eq(" + ind + ")");

             classdate.push(dateofclass);
             classtime.push(timeofclass);
             dayofclass.push(classday);


             newDateAndTime = (dayofclass[x].val() + classtime[x].val()).toString();
             var testString = (dayofclass[x].val() + classtime[x].val()).toString();
             //check to see if this string is already in the array
             if (jQuery.inArray(testString, newDateAndTime) !== -1) //if element is not fond return -1.

                 alert("Yep");
             else alert("No");

         }

     });
$(“#saveBtn”)。单击(函数(){
对于(变量x=0;x
因为
testString
不是数组。您可以使用
字符串#indexOf

if (testString.indexOf(newDateAndTime) !== -1) //if element is not fond return -1.

    alert("Yep");
else alert("No");
…或实际使用数组:

newDateAndTime = (dayofclass[x].val() + classtime[x].val()).toString();
var testString = [(dayofclass[x].val() + classtime[x].val()).toString()];
// Note ---------^-----------------------------------------------------^
if (jQuery.inArray(testString, newDateAndTime) !== -1) //if element is not fond return -1.

    alert("Yep");
else alert("No");

请注意,在第二种情况下,您将在数组中查找完全匹配的字符串(而不是子字符串匹配)。

您是对的。我用的是第一种选择。非常感谢你!旁注:
val
如果jQuery集合中有任何内容,jQuery实例上的
val
将始终返回一个字符串(如果集合为空,
undefined
)。所以没有理由使用
(dayofclass[x].val()+classtime[x].val()).toString()
;只要
dayofclass[x].val()+classtime[x].val()
就可以了(同样,除非其中一个集合可能为空,但我怀疑如果是这样的话,您不想运行该行)。