First, let’s look at the slice() method of selecting elements from an array:
Source code:
<!DOCTYPE html> <html> <body> ​ <p id="demo">Click the button to extract the second and the third elements from the array.</p> ​ <button onclick="myFunction()">Try it</button> ​ <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> ​ </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> ​ <p id="demo">Click the button to join the array elements into a string.</p> ​ <button onclick="myFunction()">Try it</button> ​ <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x=document.getElementById("demo"); x.innerHTML=fruits.join(); } </script> ​ </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> ​ <p id="demo">点击按钮将数组转为字符串并返回。</p> ​ <button onclick="myFunction()">点我</button> ​ <script> function myFunction() { var fruits = ["Banana", "Orange", "Apple", "Mango"]; var str = fruits.toString(); var x=document.getElementById("demo"); x.innerHTML= str; } </script> ​ </body> </html>
Test results:
Banana,Orange,Apple,Mango