web-dev-qa-db-fra.com

Qu'est-ce qui cause l'erreur `string.split n'est pas une fonction`?

Pourquoi est-ce que je reçois ...

Uncaught TypeError: string.split n'est pas une fonction

... quand je cours ...

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

Change ça...

_var string = document.location;
_

pour ça...

_var string = document.location + '';
_

En effet, _document.location_ est un objet Location . La valeur par défaut .toString() renvoie l'emplacement sous forme de chaîne. La concaténation déclenchera donc cette opération.


Vous pouvez également utiliser document.URL pour obtenir une chaîne.

178
user1106925

peut être

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

en supposant que vous voulez l'URL actuelle

59
chepe263

lance ça

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

vous voulez document.location.toString() ou document.location.href

11
dstarh

document.location n'est pas une chaîne.

Vous voulez probablement utiliser document.location.href ou document.location.pathname à la place.

5
Denys Séguret