Program JavaScript untuk Mengonversi Objek ke String

0
(0)

Contoh 1: Konversi Objek ke String Menggunakan JSON.stringify()

// program to convert an object to a string

const person = {
    name: 'Jack',
    age: 27
}

const result =  JSON.stringify(person);

console.log(result);
console.log(typeof result);

Keluaran

{"name":"Jack","age":27}
string

Dalam contoh di atas, JSON.stringify() metode yang digunakan untuk mengubah objek menjadi string.

Itu typeof operator memberikan tipe data dari hasil variabel.


Contoh 2: Konversi Objek ke String Menggunakan String()

// program to convert an object to a string

const person = {
    name: 'Jack',
    age: 27
}

const result1 = String(person);
const result2 = String(person['name']);

console.log(result1);
console.log(result2);

console.log(typeof result1);

Keluaran

[object Object]
Jack
string

Dalam contoh di atas, String() fungsi mengubah nilai suatu objek menjadi string.

Saat menggunakan String() fungsi pada Object, hasil konversi akan memberikan [object Object].

Itu typeof operator memberikan tipe data dari hasil variabel.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.