Home  >  Article  >  Web Front-end  >  An example of how to convert array elements into strings in JavaScript_Basic knowledge

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

WBOY
WBOYOriginal
2016-05-16 15:35:061088browse

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>   

Test results:

Orange,Lemon

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> 

Test results:

Banana,Orange,Apple,Mango

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>

Test results:

Banana,Orange,Apple,Mango 

Statement:
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