Metóda JavaScript Object toString () vracia objekt ako reťazec.
Syntax toString()
metódy je:
obj.toString()
Tu obj
je objekt.
toString () parametre
toString()
Metóda neberie žiadne parametre.
Vrátiť hodnotu z toString ()
- Vráti reťazec predstavujúci objekt.
Poznámka : Každý objekt pochádzajúci z Object
dedí toString()
a ak nie je prepísaný, vráti sa "(object )"
.
Príklad: Použitie 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.
Výkon
1010 Št 6. augusta 2020 12:08:44 GMT + 0545 (Nepálsky čas) (objekt Objekt) Daniel je buldog.
Odporúčané čítanie: JavaScript Object valueOf ()