Perché sto ricevendo ...
Uncaught TypeError: string.split non è una funzione
... quando corro ...
var string = document.location;
var split = string.split('/');
Perché sto ricevendo ...
Uncaught TypeError: string.split non è una funzione
... quando corro ...
var string = document.location;
var split = string.split('/');
Risposte:
Cambia questo...
var string = document.location;
a questa...
var string = document.location + '';
Questo perché document.locationè un oggetto Location . L'impostazione predefinita .toString()restituisce la posizione in forma di stringa, quindi la concatenazione lo attiverà.
Puoi anche usare document.URLper ottenere una stringa.
toString()invece di concatenazione hacky?
+ ''è un trucco abbastanza comune per la coercizione stringa, ma alcune persone preferiscono il toString()metodo. Non lo considererei più hacky che usare l'unario +per la conversione dei numeri.
parseInt()e parseFloat(). C'è anche Number(). Il +è più breve, naturalmente, ma meno leggibile per qualcuno non utilizzato per il codice hacky o meno esperti.
+ ''metodo non cambia nulla per me nel browser Chrome, ma lo toString()fa.
eseguire questo
// you'll see that it prints Object
console.log(typeof document.location);
vuoi document.location.toString()odocument.location.href
document.location non è una stringa.
Probabilmente vorrai usare document.location.hrefo document.location.pathnameinvece.
In clausola se, usa (). Per esempio:
stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
document.locationè un oggetto. Prova:var string=document.location.href