是什么导致错误`string.split不是函数`?

Eri*_*ric 99 javascript jquery split

我为什么要......

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

......当我跑...

var string = document.location;
var split = string.split('/');
Run Code Online (Sandbox Code Playgroud)

小智 193

改变这个......

var string = document.location;
Run Code Online (Sandbox Code Playgroud)

对...

var string = document.location + '';
Run Code Online (Sandbox Code Playgroud)

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


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

  • 调用`toString()`而不是hacky concatenation不是更清晰吗? (46认同)
  • 那就像丑陋一样.有`parseInt()`和`parseFloat()`.还有`Number()`.当然,`+`更短,但对于那些不习惯hacky代码或经验不足的人来说,可读性较差. (3认同)
  • @bažmegakapa:是的,这是优先选择的问题。“ +”是字符串强制的一种很常见的技巧,但有些人更喜欢使用“ toString()”方法。与使用一元`+`进行数字转换相比,我再也不会觉得它很笨拙。 (2认同)

che*_*263 61

也许

string = document.location.href;
arrayOfStrings = string.toString().split('/');
Run Code Online (Sandbox Code Playgroud)

假设您想要当前的网址


dst*_*arh 11

跑这个

// you'll see that it prints Object
console.log(typeof document.location);
Run Code Online (Sandbox Code Playgroud)

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


Den*_*ret 5

document.location 不是字符串。

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