139

为什么我越来越...

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

...当我跑步时...

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

4

5 回答 5

256

改变这个...

var string = document.location;

对这个……

var string = document.location + '';

这是因为document.location它是一个Location 对象。默认.toString()以字符串形式返回位置,因此连接将触发该位置。


你也可以document.URL用来获取字符串。

于 2012-04-13T18:04:11.427 回答
85

也许

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

假设你想要当前的 url

于 2012-04-13T18:05:57.367 回答
14

运行这个

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

你想要document.location.toString()document.location.href

于 2012-04-13T18:07:02.117 回答
9

document.location不是字符串。

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

于 2012-04-13T18:06:14.813 回答
1

在分句 if 中,使用(). 例如:

stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
于 2020-07-25T22:53:40.717 回答