Javascript array в строку

Array.prototype.join()

Метод join() объединяет все элементы массива (или массивоподобного объекта) в строку.

Интерактивный пример

Синтаксис

Параметры

Определяет строку, разделяющую элементы массива. В случае необходимости тип разделителя приводится к типу Строка. Если он не задан, элементы массива разделяются запятой ‘,‘. Если разделитель — пустая строка, элементы массива ничем не разделяются в возвращаемой строке.

Возвращаемое значение

Строка, содержащая все элементы массива. Если arr.length == 0 , то будет возвращена пустая строка.

Описание

Преобразует все элементы массива в строки и объединяет их в одну большую строку. Элемент массива с типом undefined или null преобразуется в пустую строку.

Примеры

Соединение массива четырьмя различными способами

В следующем примере создаётся массив a с тремя элементами, затем они четыре раза объединяются в строку: с использованием разделителя по умолчанию, запятой с пробелом, плюса, окружённого пробелами, и пустой строки.

var a = ['Ветер', 'Дождь', 'Огонь']; var myVar1 = a.join(); // присвоит 'Ветер,Дождь,Огонь' переменной myVar1 var myVar2 = a.join(', '); // присвоит 'Ветер, Дождь, Огонь' переменной myVar2 var myVar3 = a.join(' + '); // присвоит 'Ветер + Дождь + Огонь' переменной myVar3 var myVar4 = a.join(''); // присвоит 'ВетерДождьОгонь' переменной myVar4 

Соединение элементов массивоподобного объекта

В следующем примере соединяется массивоподобный объект (в данном случае список аргументов функции) с использованием вызова Function.prototype.call для Array.prototype.join .

function f(a, b, c)  var s = Array.prototype.join.call(arguments); console.log(s); // '1,a,true' > f(1, 'a', true); 

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Array.prototype.toString()

The toString() method returns a string representing the specified array and its elements.

Try it

Syntax

Return value

A string representing the elements of the array.

Description

The Array object overrides the toString method of Object . The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array] .

const arr = []; arr.join = 1; // re-assign `join` with a non-function console.log(arr.toString()); // [object Array] console.log(Array.prototype.toString.call( join: () => 1 >)); // 1 

JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

Array.prototype.toString recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString does not have delimiters, nested arrays look like they are flattened.

const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix.toString()); // 1,2,3,4,5,6,7,8,9 

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

const arr = []; arr.push(1, [3, arr, 4], 2); console.log(arr.toString()); // 1,3,,4,2 

Examples

Using toString()

const array1 = [1, 2, "a", "1a"]; console.log(array1.toString()); // "1,2,a,1a" 

Using toString() on sparse arrays

Following the behavior of join() , toString() treats empty slots the same as undefined and produces an extra separator:

Calling toString() on non-array objects

toString() is generic. It expects this to have a join() method; or, failing that, uses Object.prototype.toString() instead.

.log(Array.prototype.toString.call( join: () => 1 >)); // 1; a number console.log(Array.prototype.toString.call( join: () => undefined >)); // undefined console.log(Array.prototype.toString.call( join: "not function" >)); // "[object Object]" 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 15, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

5 Ways To Convert JavaScript Array To String

In this article, we are going to see how to convert Javascript array to string in 5 different ways. You will see converting an array to a string with commas, without commas, using the join() method, etc.

We need to convert an array to a string in JavaScript for various reasons like: the need to send an array to the server for processing, the need to store an array in local storage, the data set stored in an array to be displayed on a web page, etc.

JavaScript array to string

For your quick answer, convert the Javascript array to string using join() method .

The join() method will join all the elements of an array into a string by separating them with a specified character. Here is an example:

var arr = ["a", "b", "c", "d", "e"]; var str = arr.join(); console.log(str); // a,b,c,d,e // join array elements // without separator str = arr.join(""); console.log(str);

The code above demonstrates how you can easily convert an array to a string in JavaScript. We discuss more methods to convert an array to a string below and also explore the join() method in detail.

1. Convert Array To String Using join() Method

The join() is an array method in JavaScript. It is used to join all the elements of an array into a string by separating them with a given character.

The method takes one argument, which is the separator. The separator is used to separate the elements of an array. The default separator is a comma (,).

arr.join(); // or arr.join(separator);

After joining all the elements the string is returned.

var arr = ["a", "b", "c", "d", "e"]; // join array elements var str = arr.join(); console.log(str); // a,b,c,d,e // join with underscore str = arr.join("_"); // a_b_c_d_e console.log(str);

In the above example when we do not pass any separator, the array is joined with a comma (,) as the default separator. And when you passed underscore (_) as the separator, the array is joined with an underscore as the separator.

Let’s try adding multiple characters as the separator.

var arr = ["John", "is", "a", "good", "coder"]; var str = arr.join("###"); console.log(str);

2. Using toString() Method

The toString() method is a Javascript method that converts an array to a string by separating the elements with commas.

The method takes no arguments and returns a string.

var arr = ["John", "is", "a", "good", "coder"]; // convert array to string var str = arr.toString(); console.log(str); // John,is,a,good,coder

In the above example, the toString method converts an array to a string by separating the elements with a comma (,) .

Later if you want then you can replace these commas with any other character using the replaceAll() method.

The following example shows how to replace the commas with an underscore.

var arr = ["John", "is", "a", "good", "coder"]; // using toString() method var str = arr.toString(); str = str.replaceAll(",", "_"); console.log(str); // John_is_a_good_coder

Note: If the array element itself contains a comma then you have to take care of it using your own logic.

3. Stringifying array to string

You can directly convert an array to a string by using the JSON.stringify() method.

The method takes every element of an array wraps it in double-quotes, separates them with a comma, and returns a string with a square bracket at the beginning and a square bracket at the end.

var arr = ["John", "is", "a", "good", "coder"]; // using JSON.stringify() method var str = JSON.stringify(arr); console.log(str); // ["John","is","a","good","coder"]

JSON.stringify() method is mostly used to convert a data structure to a string before sending it to the server. Or the data sent by the server is stringified before sending it to the client.

4. Using String() Method

The String() method in Javascript is can convert any value to a string and can so do for an array. It converts an array to a string by separating the elements with commas.

The method takes a array itself as an argument and returns a string.

var arr = ["John", "is", "a", "good", "coder"]; // using String() method var str = String(arr); console.log(str); // John,is,a,good,coder

5. Using Coercion

Coercion is the process of converting a value to a different type.

In Javascript using an operator over an operand can change the data type of the operand. For example, the operator + can be used to convert a string to a number, adding an empty string to a number will convert the number to a string.

In the same way, if you add a blank array to any existing array, the existing array will be converted to a string. The same happens if you add a string to an array.

Here is an example to show this in action.

var arr = ["John", "is", "a", "good", "coder"]; var str1 = arr + []; // John,is,a,good,coder console.log(str1); console.log(typeof str1); // string var str2 = arr + ""; // John,is,a,good,coder console.log(str2); console.log(typeof str2); // string
John,is,a,good,coder string John,is,a,good,coder string

The above method methods to convert Javascript array to string can be generalized into 2 categories:

JavaScript array to string with commas

Methods that can be used to convert an array to a string with commas are:

  1. Using toString() method
  2. Using join() method
  3. Using String() method
  4. Using coercion process

JavaScript array to string without commas

Methods that can be used to convert an array to a string without commas is using the arr.join(» «) with any separator other than a comma or leave it blank.

var arr = ["Ja", "va", "S", "cript"]; var str = arr.join(""); console.log(str); // JavaScript

Conclusion

In this short guide, you have learned 5 different ways to convert Javascript array to string. Among all these methods, the join() method is robust and most commonly used for this purpose.

Источник

Читайте также:  Php pass null parameter
Оцените статью