是什么导致了‘ string.split 不是函数’错误?

为什么我..。

未捕获的 TypeError: string.split 不是一个函数

... 当我跑的时候..。

var string = document.location;
var split = string.split('/');

471311 次浏览

把这个换了。

var string = document.location;

到这个..。

var string = document.location + '';

这是因为 document.location位置对象。默认的 .toString()以字符串形式返回位置,因此串联将触发。


您还可以使用 document.URL来获取字符串。

也许吧

string = document.location.href;
arrayOfStrings = string.toString().split('/');

假设您想要当前的 url

document.location不是字符串。

您可能想使用 document.location.hrefdocument.location.pathname代替。

查查这个

// you'll see that it prints Object
console.log(typeof document.location);

你要 document.location.toString()还是 document.location.href

在小句 if 中,使用 ()。 例如:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...