Home > Web Front-end > JS Tutorial > body text

How to use join method in js to convert elements in array into string

醉折花枝作酒筹
Release: 2021-08-10 16:43:38
Original
3385 people have browsed it

In the previous article we learned how to set the array length, please see "How to set the array length in javascript". This time we will learn about the method of converting array elements into strings. You can refer to it if necessary.

We have learned a lot about array methods. Today we will introduce a method to convert array elements into strings.

First let’s look at a small example.

<script>
var arr = new Array(3); 
arr[0] = "one";
arr[1] = "two";
arr[2] = "three";
var nums = arr.join();
console.log(nums);
console.log(arr);
</script>
Copy after login

The result of this little chestnut is

How to use join method in js to convert elements in array into string

Let’s look at this result. The first one is a string, and the second one is an array. Let’s look at the code again. The first one is where we used the join() method, and the second one is our original array. After knowing a little bit about the join() method, let's study the join method in detail.

join() method joins all elements of an array (or an array-like object) into a string and returns this string. If the array has only one item, that item will be returned without a delimiter.

Let’s take a look at the syntax format of this method.

数组名称.join(指定要使用的分隔符。如果省略该参数,则使用逗号作为分隔符)
Copy after login

The join() method will return a string. This string is generated by converting each element of arrayObject to a string, then concatenating the strings, and inserting the separator string between the two elements. If separator is the empty string (""), there will be no characters between any elements.

The join() method can convert an array into a string, but it can specify the delimiter. This is just like our example above. When calling the join() method, we did not pass a parameter as a separator to join each element. So it uses commas as the delimiter by default when outputting.

That’s all. If you need it, you can read: javascript advanced tutorial

The above is the detailed content of How to use join method in js to convert elements in array into string. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!