在JavaScript中,可以使用split()和Array.from()方法將字符串轉(zhuǎn)換為字符串?dāng)?shù)組。下面本篇文章就來給大家介紹一下,希望對大家有所幫助。

方法1:使用split()方法
split()方法用于將給定字符串拆分為字符串?dāng)?shù)組,該方法是使用參數(shù)中提供的指定分隔符將其分隔為子字符串。
語法:
str.split(separator, limit)
示例:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="str">Welcome to here!</p>
<p id="arr"></p>
<script>
var str =document.getElementById("str").innerHTML;
document.getElementById("arr").innerHTML = str.split("");
</script>
</body>
</html>
輸出:
Welcome to here!
W,e,l,c,o,m,e, ,t,o, ,h,e,r,e,!
方法2:使用Array.from()方法
Array.from()方法是javascript中的一個內(nèi)置函數(shù),它從給定的數(shù)組創(chuàng)建一個新的數(shù)組實(shí)例。對于字符串,字符串的每個字母表都會轉(zhuǎn)換為新數(shù)組實(shí)例的元素;對于整數(shù)值,新數(shù)組實(shí)例simple將獲取給定數(shù)組的元素。
語法:
Array.from(str)
示例:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="str">Welcome to here!</p>
<p id="arr"></p>
<script>
var str = document.getElementById("str").innerHTML;
? ? ? ? ? ? document.getElementById("arr").innerHTML = Array.from(str);
</script>
</body>
</html>
輸出:
Welcome to here!
W,e,l,c,o,m,e, ,t,o, ,h,e,r,e,!
更多前端開發(fā)知識,請查閱 HTML中文網(wǎng) !!