为什么字符串搜索对某些字符串有效而对其他字符串无效

Why does string.search work for some strings and not others?

本文关键字:字符串 其他 无效 有效 搜索 为什么      更新时间:2023-09-26

在以下代码中,第一次搜索工作正常,但第二次搜索返回错误:TypeError:表达式"str.search"[]的结果不是函数。这是令人惊讶的,因为我期望结果是一个数值,而不是一个函数。我没有看到其他问题有同样的错误,所以我希望这是一个明显的初学者错误。

function loadT() {
  var pos;
  var str;
  str=window.name;
  pos= str.search(" ");
  if (pos > -1) {
    window.name = str.slice(0,pos);
  }
  str=window.location;
  pos= str.search("#");
  if (pos > -1) {
    sender = str.slice(pos+1);
  }
 }

window.location不是字符串,但在Object上,您应该强制转换它:

str = "" + window.location;