先來看看從一個陣列中選擇元素的方法slice():
原始碼:
<!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>
測試結果:
Orange,Lemon
我們可以用陣列的元素組成字串,相關的join()方法使用範例:
原始碼:
<!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>
測試結果:
Banana,Orange,Apple,Mango
直接轉換陣列到字串則可以用toString()方法:
原始碼:
<!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>
測試結果:
Banana,Orange,Apple,Mango