La méthode JavaScript Object toString () renvoie l'objet sous forme de chaîne.
La syntaxe de la toString()
méthode est:
obj.toString()
Voici obj
un objet.
Paramètres toString ()
La toString()
méthode ne prend aucun paramètre.
Valeur renvoyée par toString ()
- Renvoie une chaîne représentant l'objet.
Remarque : chaque objet issu de l' Object
héritage toString()
et s'il n'est pas remplacé, il retourne "(object )"
.
Exemple: utilisation de 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.
Production
1010 jeu 06 août 2020 12:08:44 GMT + 0545 (heure du Népal) (objet objet) Daniel est un bouledogue mâle.
Lecture recommandée: objet JavaScript valueOf ()