Il metodo JavaScript Object toString () restituisce l'oggetto come una stringa.
La sintassi del toString()
metodo è:
obj.toString()
Ecco obj
un oggetto.
parametri toString ()
Il toString()
metodo non accetta parametri.
Valore restituito da toString ()
- Restituisce una stringa che rappresenta l'oggetto.
Nota : ogni oggetto discendente da Object
eredita toString()
e, se non viene sovrascritto, restituisce "(object )"
.
Esempio: utilizzo di toString ()
// built-in objects let num = 10; // number takes in optional radix argument (numeral base) console.log(num.toString(2)); // "1010" in binary console.log(new Date().toString()); // Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time) // overriding default toString(), custom object function Dog(name, breed, sex) ( this.name = name; this.breed = breed; this.sex = sex; ) dog1 = new Dog("Daniel", "bulldog", "male"); console.log(dog1.toString()); // (object Object) Dog.prototype.toString = function dogToString() ( return `$(this.name) is a $(this.sex) $(this.breed).`; ); console.log(dog1.toString()); // Daniel is a male bulldog.
Produzione
1010 Thu Aug 06 2020 12:08:44 GMT + 0545 (Nepal Time) (Object Object) Daniel è un bulldog maschio.
Letture consigliate: oggetto JavaScript valueOf ()