舉例講解JavaScript中將數(shù)組元素轉(zhuǎn)換為字符串的方法
更新時(shí)間:2015年10月25日 15:00:22 投稿:goldensun
這篇文章主要介紹了JavaScript中將數(shù)組元素轉(zhuǎn)換為字符串的方法,是JS入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下
首先來看一下從一個(gè)數(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">點(diǎn)擊按鈕將數(shù)組轉(zhuǎn)為字符串并返回。</p>
<button onclick="myFunction()">點(diǎn)我</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實(shí)現(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中實(shí)現(xiàn)字符串和數(shù)組的相互轉(zhuǎn)化詳解
- js數(shù)組常見操作及數(shù)組與字符串相互轉(zhuǎn)化實(shí)例詳解
- javascript實(shí)現(xiàn)的字符串轉(zhuǎn)換成數(shù)組操作示例
相關(guān)文章
javascript基礎(chǔ)之查找元素的詳細(xì)介紹(訪問節(jié)點(diǎn))
常用jQuery的話我們知道,jQuery有非常強(qiáng)大的選擇器來查找元素(也稱作訪問節(jié)點(diǎn)),例如:基本選擇器、層次選擇器、過濾選擇器、屬性選擇器等2013-07-07
怎么通過onclick事件獲取js函數(shù)返回值(代碼少)
這篇文章主要介紹了怎么通過onclick事件獲取js函數(shù)返回值,需要的朋友可以參考下2015-07-07
原生JavaScript來實(shí)現(xiàn)對dom元素class的操作方法(推薦)
這篇文章主要介紹了原生JavaScript來實(shí)現(xiàn)對dom元素class的操作方法,提供了代碼toggleClass的測試?yán)?,具體操作步驟大家可查看下文的詳細(xì)講解,感興趣的小伙伴們可以參考一下。2017-08-08

