Javascript objekts toString ()

Metode JavaScript Object toString () atgriež objektu kā virkni.

Metodes sintakse toString()ir šāda:

 obj.toString()

Šeit objir objekts.

toString () parametri

toString()Metode neveic nekādus parametrus.

Atgriezt vērtību no toString ()

  • Atgriež virkni, kas attēlo objektu.

Piezīme . Katrs objekts ir cēlies no Objectmantojuma toString()un, ja netiek ignorēts, tas atgriežas "(object )".

Piemērs: toString () izmantošana

 // 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.

Rezultāts

 1010 ceturtdiena, 2020. gada 6. augusts 12:08:44 GMT + 0545 (Nepālas laiks) (objekta objekts) Daniels ir vīriešu buldogs.

Ieteicamā literatūra: JavaScript Object valueOf ()

Interesanti raksti...