首頁  >  文章  >  web前端  >  舉例說明JavaScript中將陣列元素轉換為字串的方法_基礎知識

舉例說明JavaScript中將陣列元素轉換為字串的方法_基礎知識

WBOY
WBOY原創
2016-05-16 15:35:061151瀏覽

先來看看從一個陣列中選擇元素的方法slice():
原始碼:

<!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>   

測試結果:

Orange,Lemon

我們可以用陣列的元素組成字串,相關的join()方法使用範例:

原始碼:

<!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> 

測試結果:

Banana,Orange,Apple,Mango

直接轉換陣列到字串則可以用toString()方法:
原始碼:

<!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>

測試結果:

Banana,Orange,Apple,Mango 

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn