indexOf 认字失败

indexOf failing to recognize word

不确定为什么 indexOf 无法识别单词 'error'。

PHP 脚本返回如下文本:

echo "Error: user was not updated.";

在 JQuery 中,我有以下内容:

$.post('api/editUser.php', {robj:robj}, function(data){
  if(data.indexOf('Error')){
    console.log("bad - " + data);
  }
  else{
    console.log("good - " + data);
  }
});

使用上面的方法,我不断得到输出“good - Error: user was not updated”

控制台应显示:“错误 - 错误:用户未更新”

是indexOf的问题吗?

我做错了什么?

indexOf returns 0 因为你的单词被放置在字符串中的第一个单词。零是 falsy 值,所以尝试重写以检查 indexoOf() != -1:

if( data.indexOf('Error')!= -1){
   console.log("bad - " + data);
}
else{
   console.log("good - " + data);

As mdn says:

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

如果你尝试记录 indexOf return 你会看到它 returns 0

console.log( "Error: user was not updated.".indexOf("Error") )

然后做 if (0) 你会看到你进入 else

if (0) {console.log("in if")} else {console.log("in else")}

发生这种情况是因为 0 是一个 falsy value,这意味着在强制转换为布尔值时被视为 false 的值


要得到你想要的,你可以使用 indexOf === 0 如果任何消息 "Error" 不是在开始是一个有效的消息,或者 includes 如果任何消息包含 "Error"无论是position

都是无效的

console.log( "Error: user was not updated.".indexOf("Error") === 0 )
console.log( "Error: user was not updated.".includes("Error") )
console.log( "message with Error at the center".indexOf("Error") === 0 )
console.log( "message with Error at the center".includes("Error") )

尝试使用 search()。它主要用于正则表达式,但如果您使用纯文本,它仍然可以工作,因为它将是一个有效的正则表达式。 请注意,它的性能不如 indexOf,因为它被视为 RegEx.

P.s。我知道您知道来自服务器的确切文本,但为了保持一致性,将所有内容都小写总是更安全。

这应该有效:

$.post('api/editUser.php', {robj:robj}, function(data){
  if(data.toLowerCase().search('error')){
    console.log("bad - " + data);
  }
  else{
    console.log("good - " + data);
  }
});