Skip to content →

[JS] Join分割連接 陣列轉換字串

Join(separator):
不改變原來陣列 ,用separator將陣列內的元素連接成字串。
String.split()作用相反 。

var arr = [“A”, “B”, “C”, “D”, “E”];
arr.join();       //A,B,C,D,E  ,省略separator則用,作分隔
arr.join()[2];     //B      ,還是字串
arr.join(0);     //A0B0C0D0E
arr.splice(0)[2];   //B
arr.join(” “);     //A B C D E
arr.join(” “)[2];    //B
arr.join(“”);     //ABCDE
arr.join(“”)[2];    //C


String.split() 和 Array.join() 也可以拿來替換文字

var str = “Hi SPLIT, Have A Nice Day.”;
str.split(“a”).join(“~”);      
//Hi SPLIT, H~ve A Nice D~y.  ,還是字串

Published in JS

Comments are closed.