DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript基礎知識 >> 舉例講解JavaScript中將數組元素轉換為字符串的方法
舉例講解JavaScript中將數組元素轉換為字符串的方法
編輯:JavaScript基礎知識     

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

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved