Created
December 27, 2021 06:24
-
-
Save hoyangtsai/cf6ba3ff5513dbec31aea688af59adbe to your computer and use it in GitHub Desktop.
Convert array to a string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 1. Use .toString() | |
['a', 'b', 'c'].toString(); // 'a,b,c' | |
// 2. Coerce to string | |
['a', 'b', 'c'] + []; // 'a,b,c' | |
['a', 'b', 'c'] + ''; // 'a,b,c' | |
// 3. Use .join() | |
['a', 'b', 'c'].join(); // 'a,b,c' (defaults to ',' separator) | |
['a', 'b', 'c'].join(''); // 'abc' | |
['a', 'b', 'c'].join('-'); // 'a-b-c' | |
// 4. Use JSON.stringify() | |
JSON.stringify(['a', [1], 'b', 'c']); // '['a', [1], 'b','c']' | |
// 5. Manually, if can't use built-in method... | |
function arrayToString(arr) { | |
let str = ''; | |
arr.forEach(function(i, index) { | |
str += i; | |
if (index != (arr.length - 1)) { | |
str += ','; | |
}; | |
}); | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code from William Vincent blog, JavaScript: Convert Array to a String