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

时间:2014-05-14 15:32:39

标签: jquery asp.net

为什么我的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");

         }

     });

1 个答案:

答案 0 :(得分:1)

因为testString不是数组。您要么使用String#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");

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

相关问题