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

An example of how to convert array elements into strings in JavaScript_Basic knowledge

WBOY
Release: 2016-05-16 15:35:06
Original
1143 people have browsed it

First, let’s look at the slice() method of selecting elements from an array:
Source code:

<!DOCTYPE html>
<html>
<body>
&#8203;
<p id="demo">Click the button to extract the second and the third elements from the array.</p>
&#8203;
<button onclick="myFunction()">Try it</button>
&#8203;
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
var citrus = fruits.slice(1,3);
var x=document.getElementById("demo");
x.innerHTML=citrus;
}
</script>
&#8203;
</body>
</html>   

Copy after login

Test results:

Orange,Lemon
Copy after login

We can use the elements of the array to form a string. Related join() method usage examples:

Source code:

<!DOCTYPE html>
<html>
<body>
&#8203;
<p id="demo">Click the button to join the array elements into a string.</p>
&#8203;
<button onclick="myFunction()">Try it</button>
&#8203;
<script>
function myFunction()
{
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var x=document.getElementById("demo");
x.innerHTML=fruits.join();
}
</script>
&#8203;
</body>
</html> 

Copy after login

Test results:

Banana,Orange,Apple,Mango

Copy after login

To directly convert an array to a string, you can use the toString() method:
Source code:

<!DOCTYPE html>
<html>
<body>
&#8203;
<p id="demo">点击按钮将数组转为字符串并返回。</p>
&#8203;
<button onclick="myFunction()">点我</button>
&#8203;
<script>
function myFunction()
{
 var fruits = ["Banana", "Orange", "Apple", "Mango"];
 var str = fruits.toString();
 var x=document.getElementById("demo");
 x.innerHTML= str;
}
</script>
&#8203;
</body>
</html>

Copy after login

Test results:

Banana,Orange,Apple,Mango 
Copy after login

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