Can we stringify a Javascript array in same way PHP implode('separator', $array) does?
I am having a JavaScript array and I want to convert this array into string with a separator, in a way PHP implode does.
e.g.
var daysArr = [];
daysArr.push('monday');
daysArr.push('tuesday');
I want开发者_Python百科 to get "monday*tuesday"
How can we achieve this?
Thx.
Try using this
daysArr.join('*');
NameOfArray.join('separator');
array.join(separator)
Use JavaScript function join
daysArr.join('*');
var arr = new Array();
arr[0] = "1";
arr[1] = "2";
alert(arr.join("*"));
Demo example.
This function should do it
<script>
var daysArr = [];
daysArr.push('monday');
daysArr.push('tuesday');
function implode(arr, sep) {
//Output string
output = '';
//Counter
j = 1;
for (i in arr) {
//Append
output += arr[i];
//Add seperater if not the last item
if (j != arr.length) {
output += sep;
}
j++;
}
//Return output
return output;
}
alert(implode(daysArr, ','));
</script>
精彩评论