JS字符串與數組的相互轉換
在今天的工作中遇到一個問題,需要將string字符串轉換為數組,在此記錄一下。
博客參考文章:https://www.cnblogs.com/smzd/p/11792878.html
1、字符串轉換為數組
//customerLabelName="實施前、實施中、實施后",以split的字符進行切割
var customerLabelNameResult = data[i].customerLabelName.split("、");
var customerLabelColorNameResult = data[i].customerLabelColorName.split("、");
//輸出結果為:customerLabelNameResult:實施前,實施中,實施后
console.log("customerLabelNameResult:" + customerLabelNameResult);
for (let j = 0; j < customerLabelNameResult.length; j++) {
html += "<div style='" + customerLabelColorNameResult[j] + "'>" + customerLabelNameResult[j] + "</div>"
}
2、數組轉換為字符串
//customerLabelNameResult=[實施前,實施中,實施后]
var arrayToString = customerLabelNameResult.join(';');
//輸出結果為:arrayToString:實施前;實施中;實施后
console.log("arrayToString:" + arrayToString);