Javascript object methods tostring

JavaScript Object toString method — convert a JavaScript object into a string

JavaScript Object class has the toString() method that returns a string representing the object where you call the method.

But because an object can have many properties, JavaScript will return an «[object Type]» string instead of the object keys and properties.

Consider the following code:

Logically, you might expect that the output of the toString() method above as .

Instead, JavaScript returns a string in the format of «[object Type]» because it considers the object Type better represents what the object is.

I do think it’s strange, but this is based on the ECMAScript 15.2.4.2 specification for the toString() method that says:

Return the String value that is the result of concatenating the three Strings “[object “, class, and “]”.

The same [object Object] will be returned for objects generated from functions and classes:

Fortunately, you can override the toString() method to return unique information about the object:

The same can be done for JavaScript objects created from functions and classes:

For a class-based object, you add the toString() method in the class body.

For a function-based object, you override the function’s prototype.toString method.

But overriding the toString() method of each object you define in your source code is very tedious.

Your code will become more complex when you need to make the toString() method return a dynamic value based on the property key passed into the method.

Instead of overriding the toString() method, it’s better to use the JSON.stringify() method to return a string representing your object.

Here’s how the JSON.stringify() method works:

The JSON.stringify() function converts the object you pass as its argument into a JSON text format.

You can even control the white space used to format the string:

The second parameter of the JSON.stringify() method is used to add a function or an array to manipulate the object before turning it into a string.

For example, you can convert the object name value to uppercase:

If you only need to control the white space for the returned string, you can pass null as the second argument of the stringify() method.

Now you’ve learned how the JavaScript Object.toString() method works and how you can represent your objects with more informative strings.

Feel free to use the code in this tutorial for your projects. 😉

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

.to String ( )

Метод to String ( ) преобразует объект в строковое представление. Метод автоматически вызывается JavaScript, когда объект нужно представить в текстовом виде.

Если метод не переопределён, то он возвращает строку формата [object тип ] , где тип — это строка, которая уточняет тип объекта. В подавляющем большинстве вы будете видеть вывод [object Object ] .

Пример

Скопировать ссылку «Пример» Скопировано

 const book =  title: 'JavaScript: the good parts', author: 'Douglas Crockford'> console.log(`Сейчас читаю $`)// Сейчас читаю [object Object] const book =  title: 'JavaScript: the good parts', author: 'Douglas Crockford' > console.log(`Сейчас читаю $book>`) // Сейчас читаю [object Object]      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Метод вызывается без аргументов. Возвращает строковое представление объекта.

Как понять

Скопировать ссылку «Как понять» Скопировано

Существует соглашение, что метод to String ( ) вызывается JavaScript автоматически, если объект находится в контексте, где он должен быть представлен в виде строки. Чаще всего это случаи, связанные с печатью данных на экран или в консоль браузера.

Объекты, в отличие от примитивных типов, сложно преобразовывать в строку. Объект может содержать произвольное количество полей и без программиста непонятно, какие из них важные. Поэтому стандартная реализация метода to String ( ) представляет собой заглушку, печатающую ‘ [ object Object ] ‘ .

Многие структуры данных, базирующиеся на объекте Object , содержат собственные реализации этого метода. Например, Number преобразует число в строку в указанной системе счисления, а массив выводит список элементов через запятую.

Переопределение стандартной реализации

Скопировать ссылку «Переопределение стандартной реализации» Скопировано

Стандартная реализация метода to String ( ) не даёт достаточно информации об объекте даже для использования в отладке программы. Программисты могут переопределить метод to String ( ) , чтобы выводить необходимые данные.

Если мы работаем в ООП стиле, то классу нужно просто добавить метод to String ( ) :

 class Book  title = '' author = '' constructor(title, author)  this.title = title this.author = author > toString()  return `«$», автор $` >> const book = new Book('Палата №6', 'А. П. Чехов')console.log(`Читаю $`)// Читаю «Палата №6», автор А. П. Чехов class Book  title = '' author = '' constructor(title, author)  this.title = title this.author = author > toString()  return `«$this.title>», автор $this.author>` > > const book = new Book('Палата №6', 'А. П. Чехов') console.log(`Читаю $book>`) // Читаю «Палата №6», автор А. П. Чехов      

Если вы предпочитаете работать в функциональном стиле, то придётся создать новый тип объекта и переопределить метод to String ( ) в прототипе:

 function Book(title, author)  this.title = title this.author = author> Book.prototype.toString = function()  return `«$», автор $`> const book = new Book('Палата №6', 'А. П. Чехов')console.log(`Читаю $`)// Читаю «Палата №6», автор А. П. Чехов function Book(title, author)  this.title = title this.author = author > Book.prototype.toString = function()  return `«$this.title>», автор $this.author>` > const book = new Book('Палата №6', 'А. П. Чехов') console.log(`Читаю $book>`) // Читаю «Палата №6», автор А. П. Чехов      

Под капотом JavaScript обе реализации идентичны и отличаются только использованным синтаксисом.

На практике

Скопировать ссылку «На практике» Скопировано

Николай Лопин советует

Скопировать ссылку «Николай Лопин советует» Скопировано

🛠 На практике метод to String ( ) переопределяют нечасто.

Метод не подходит для вывода данных в интерфейсе из-за негибкости, для интерфейса используют специальные библиотеки, такие как React и его альтернативы. Метод отлично подходит для отладочной информации, но современные инструменты разработчика в браузере умеют выводить объект в консоль интерактивно, с возможностью просмотра содержимого.

Источник

The `toString()` Function in JavaScript

Most JavaScript objects and primitive values have a toString() function that converts the value to a string. Many built-in methods use toString() under the hood, like the browser’s alert() function.

Primitives

JavaScript number primitives have a toString() function that converts the number to a string. This is one of the most common uses for toString() :

const num = 42; num.toString(); // '42' typeof num.toString(); // 'string' // Can also use `toString()` on a number literal as long as you // use parentheses. (42).toString(); // '42'

All primitive values except null and undefined have a toString() function: strings, numbers, booleans, BigInts, and symbols.

// String: 'Hello'.toString(); // 'Hello' // Number: (42).toString(); // '42' // Boolean: true.toString(); // 'true' // BigInt: 42n.toString(); // '42' // Symbol: Symbol('test').toString(); // 'Symbol(test)'

The important takeaway is that it is safe to call toString() on an arbitrary JavaScript value as long as that value is not null or undefined . The easiest way to check is to use == null : the most common use for == is that v == null is shorthand for v === null || v === undefined .

if (v != null) < // Won't throw an error, unless you wrote a custom `toString()` that throws v.toString(); >

Objects

The Object class in JavaScript is the base class for all objects, and it has a simple toString() method that usually prints [object Object] :

// Equivalent to `const obj = <>;` const obj = new Object(); obj.toString(); // '[object Object]'

The [object Object] output is often confusing to beginners because they want to see the object’s keys and values. You can loop over the object’s keys and values yourself, but the easiest one-liner is to use JSON.stringify() .

const obj = < name: 'Jean-Luc Picard', rank: 'Captain' >; // '' console.log(JSON.stringify(obj));

If you define a JavaScript class, you can overwrite the toString() function to return whatever you want:

class MyClass < toString() < return 'Hello, World!'; > > const obj = new MyClass(); obj.toString(); // 'Hello, World!'

toString() Parameters

Some toString() functions take parameters, most notably numbers and Node.js buffers.

The toString() function for JavaScript numbers takes a radix parameter that defines the base of the numeral system. In other words, num.toString(2) converts the number to a binary number string, num.toString(10) converts the number to a base-10 string, and num.toString(16) converts the number to a hexadecimal string.

(3).toString(2); // '11' (42).toString(10); // '42' (29).toString(16); // '1d'

The Node.js buffer toString() function takes an encoding parameter that is usually one of ‘utf8’, ‘hex’, or ‘base64’. This determines how the raw data in the buffer is encoded.

const fs = require('fs'); const buf = fs.readFileSync('./package.json'); buf.toString('utf8'); // '< "name": "masteringjs.io", . >'

More Fundamentals Tutorials

Источник

Читайте также:  What is homepage in html
Оцените статью