首先來看一下從一個數組中選擇元素的方法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