Wat veroorzaakt de fout `string.split is geen functie`?

Waarom krijg ik…

Uncaught TypeError: string.split is geen functie

…wanneer ik ren…

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

Antwoord 1, autoriteit 100%

Wijzig dit…

var string = document.location;

naar dit…

var string = document.location + '';

Dit komt omdat document.locationeen Location-objectis . De standaard .toString()retourneert de locatie in tekenreeksvorm, dus de aaneenschakeling zal dat activeren.


U kunt ook document.URLgebruiken om krijg een string.


Antwoord 2, autoriteit 32%

misschien

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

ervan uitgaande dat u de huidige url wilt


Antwoord 3, autoriteit 6%

voer dit uit

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

je wilt document.location.toString()of document.location.href


Antwoord 4, autoriteit 3%

document.locationis geen tekenreeks.

U wilt waarschijnlijk in plaats daarvan document.location.hrefof document.location.pathnamegebruiken.


Antwoord 5

Gebruik in clausule als ().
Bijvoorbeeld:

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

Other episodes