DIV CSS 佈局教程網

join:把陣列所有元素拼成一個字串
編輯:關於JavaScript     

join() 把陣列元素用指定的分隔符號串接成一個字串。它是 split() 的反操作,兩者常常成對出現。

範例

<!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>

執行結果:

Banana,Orange,Apple,Mango

自訂分隔符號

不傳參數時預設用逗號分隔,但你可以給任何字串:

var arr = ["2026", "08", "26"];

arr.join();      // "2026,08,26"
arr.join("-");   // "2026-08-26"
arr.join("");    // "20260826"     空字串 = 直接黏在一起
arr.join(" / "); // "2026 / 08 / 26"

join("") 是把字元陣列重組回字串最直覺的寫法,例如 "hello".split("").reverse().join("") 就能反轉字串。

兩個邊界行為

陣列中的 null 與 undefined 會被轉成空字串,而不是 "null" 這個字:

[1, null, 3, undefined].join("-");   // "1---3"

巢狀陣列也只會被 toString() 一層,不會遞迴展開:

[1, [2, 3], 4].join("-");   // "1-2,3-4"

這兩個行為在處理不確定資料時容易出乎意料,記得先清理陣列內容。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved