本文實例講述了JavaScript將數組轉換成CSV格式的方法。分享給大家供大家參考。具體分析如下:
JavaScript中數組對象的valueOf方法可以將數組的值輸出為逗號分割的字符串,下面的代碼演示了如何將數組抓換成逗號和豎線分割的字符串
var fruits = ['apple', 'peaches', 'oranges', 'mangoes']; var str = fruits.valueOf(); //輸出結果: apple,peaches,oranges,mangoes
如果希望使用豎線|分割
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
var str = fruits.join("|");
//print str: apple|peaches|oranges|mangoes
完整演示代碼如下
Click here to convert fruits array to CSV:
<button onclick="javsacript:convert()">Convert to CSV</button>
<br>
<pre>var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
</pre>
<script>
function convert() {
var fruits = ['apple', 'peaches', 'oranges', 'mangoes'];
var str = fruits.valueOf();
alert(str);
}
</script>
希望本文所述對大家的javascript程序設計有所幫助。