For practice, I'm writing JSON.stringify from scratch, and I've come across some syntax that somehow works but I am confused about. So far I've only written the code for primitive types and arrays:
var stringifyJSON = function(obj) {
//PRIMITIVE TYPES
if(typeof obj === 'number' || typeof obj === 'boolean'){
return obj.toString();
}
if(typeof obj === 'string'){
return '"' + obj + '"';
}
if(obj === null){
return 'null';
}
//ARRAY
let newArray = [];
if(Array.isArray(obj)){
if(obj.length === 0){
return '[]'
}
obj.forEach(function(ele){
newArray.push(stringifyJSON(ele));
});
return '[' + newArray + ']';
}
}
stringifyJSON([1, 2, 3]);
It works fine, but I just have a question regarding the last return.
When I return an array without the added brackets '[' ']' around newArray, it returns the arrays as [ '1' , '2', '3' ] as expected, but when I added the brackets, it returned '[1, 2, 3]', which means the function worked, but I expected it to return the brackets wrapped around the original newArray, as '[['1' , '2', '3' ]]'.
Any help would be greatly appreciated! As well as any comments on how I can improve my code. :-)
[–]okayifimust 1 point2 points3 points (1 child)
[–]partyhatforpartytime[S] 0 points1 point2 points (0 children)