Get the App
SLTechnology News&Howtos  ›  Development  › 

How to convert an array to a string by JavaScript

Shulou Source: shulou.com Published: 2022-06-01 05:18:34 09月11日 Update

This article mainly explains "how to convert an array into a string by JavaScript". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "JavaScript how to convert an array into a string".

The power of JavaScript arrays is hidden in array methods.

Convert an array to a string

The JavaScript method toString () converts an array to a comma-delimited string of array values.

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Document.getElementById ("demo"). InnerHTML = fruits.toString ()

Result

Banana,Orange,Apple,Mango

The join () method can also combine all array elements into a single string.

It behaves like toString (), but you can also specify the delimiter:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Document.getElementById ("demo"). InnerHTML = fruits.join ("*")

Result

Banana * Orange * Apple * Mango

Popping and Pushing

When working with arrays, it is easy to delete elements and add new elements.

Popping and Pushing refer to:

Pops an item from an array or pushes it into an array.

Popping

The pop () method removes the last element from the array:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits.pop (); / / remove the last element ("Mango") from fruits

The pop () method returns the value of "popped":

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

The value of var x = fruits.pop (); / / x is "Mango"

Pushing

The push () method (at the end of the array) adds a new element to the array:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Fruits.push ("Kiwi"); / / add a new element to fruits

The push () method returns the length of the new array:

Example

Var fruits = ["Banana", "Orange", "Apple", "Mango"]

Var x = fruits.push ("Kiwi"); the value of / / x is 5

At this point, I believe you have a deeper understanding of "how JavaScript converts arrays into strings". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Array method element character string instance content result project learning practical deeper interest delimiter power practicality practicality simple operation more friends Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Apple Shulou Tech Info OPPO Reno NVidia