舉例講解JavaScript中將數(shù)組元素轉(zhuǎn)換為字符串的方法
更新時間:2015年10月25日 15:00:22 投稿:goldensun
這篇文章主要介紹了JavaScript中將數(shù)組元素轉(zhuǎn)換為字符串的方法,是JS入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
首先來看一下從一個數(shù)組中選擇元素的方法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>
測試結(jié)果:
Orange,Lemon
我們可以用數(shù)組的元素組成字符串,相關(guān)的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>
測試結(jié)果:
Banana,Orange,Apple,Mango
直接轉(zhuǎn)換數(shù)組到字符串則可以用toString()方法:
源代碼:
<!DOCTYPE html>
<html>
<body>
<p id="demo">點擊按鈕將數(shù)組轉(zhuǎn)為字符串并返回。</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>
測試結(jié)果:
Banana,Orange,Apple,Mango
您可能感興趣的文章:
- js數(shù)組與字符串的相互轉(zhuǎn)換方法
- js實現(xiàn)字符串和數(shù)組之間相互轉(zhuǎn)換操作
- 把json格式的字符串轉(zhuǎn)換成javascript對象或數(shù)組的方法總結(jié)
- JavaScript 字符串與數(shù)組轉(zhuǎn)換函數(shù)[不用split與join]
- js以分隔符分隔數(shù)組中的元素并轉(zhuǎn)換為字符串的方法
- javascript字符串與數(shù)組轉(zhuǎn)換匯總
- js冒泡法和數(shù)組轉(zhuǎn)換成字符串示例代碼
- js中實現(xiàn)字符串和數(shù)組的相互轉(zhuǎn)化詳解
- js數(shù)組常見操作及數(shù)組與字符串相互轉(zhuǎn)化實例詳解
- javascript實現(xiàn)的字符串轉(zhuǎn)換成數(shù)組操作示例
相關(guān)文章
JavaScript lastIndexOf方法入門實例(計算指定字符在字符串中最后一次出現(xiàn)的位置)
這篇文章主要介紹了JavaScript字符串對象的lastIndexOf方法入門實例,lastIndexOf方法用于計算指定字符在字符串中最后一次出現(xiàn)的位置,需要的朋友可以參考下2014-10-10

