Javascript 是什么导致错误`string.split is not a function`?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10145946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:03:47  来源:igfitidea点击:

What is causing the error `string.split is not a function`?

javascriptjquerysplit

提问by Eric

Why am I getting...

为什么我越来越...

Uncaught TypeError: string.split is not a function

未捕获的类型错误:string.split 不是函数

...when I run...

...当我跑...

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

回答by

Change this...

改变这...

var string = document.location;

to this...

到这...

var string = document.location + '';

This is because document.locationis a Location object. The default .toString()returns the location in string form, so the concatenation will trigger that.

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



You could also use document.URLto get a string.

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

回答by chepe263

maybe

也许

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

assuming you want the current url

假设您想要当前的网址

回答by dstarh

run this

运行这个

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

you want document.location.toString()or document.location.href

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

回答by Denys Séguret

document.locationisn't a string.

document.location不是字符串。

You're probably wanting to use document.location.hrefor document.location.pathnameinstead.

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