indexOf()函数总是返回零,即使有相同的字符串

indexOf() function always return zero even have the same string

本文关键字:字符串 函数 返回 indexOf      更新时间:2023-09-26

我在javascript中有一个变量

var hidden = "class_code,other";

然后ajax返回值

$.ajax({
type: "post",
data: $("#myform").serialize,
success: function(data){
    if(hidden.indexOf(data)){
    //mycode here
 }
}
});

,但它不起作用,所以我尝试使用alert()来打印hidden.indexOf(data),它总是返回0,所以我尝试提醒数据,它返回"class_code"

为什么我的脚本不工作,即使隐藏的变量是包含数据?

indexOf返回匹配字符串开始的位置。因为class_codeclass_code,other的开头,所以这是0。当没有找到字符串时,它返回-1。测试是否找到字符串的正确方法是:

if (hidden.indexOf(data) != -1)

。indexOf正在工作-字符串"class_code"从字符串"class_code,other"的第0个索引开始。如果不包含字符串,它将返回-1