javascript字串和陣列轉換

企業獵人發表於2016-07-17
toString()方法返回一個包含陣列中所有元素,且元素之間以逗號隔開的字串,該方法在將數值作為字串使用時強制呼叫,且無須顯示宣告此方法的呼叫。
 
例項:
<script type="text/javascript">
<!--
var arr = new Array("first","Second","Third","Forth");
var str2  = arr.toString();
var str1 = arr.join();
var str3 = arr.join(" ");
document.write(str1+"<br>");
document.write(str2+"<br>");
document.write(str3+"<br>");
-->

</script>

輸出:

first,Second,Third,Forth
first,Second,Third,Forth
first Second Third Forth


將字串轉為陣列,用split()

<script>

  var str = "tom&john&leo";

  var strArray = str.split(&);//strarray = ["tom","john","leo"];



</script>


相關文章