2 回答

TA貢獻1895條經驗 獲得超3個贊
對于數組,對項目采用遞歸方法。
const
json_encode = (input) => {
if (typeof input === "string") return `"${input}"`;
if (typeof input === "number") return `${input}`;
if (Array.isArray(input)) return `[${input.map(json_encode)}]`;
};
console.log(json_encode([1, 'foo', [2, 3]]));
console.log(JSON.parse(json_encode([1, 'foo', [2, 3]])));

TA貢獻1828條經驗 獲得超6個贊
您已經擁有將標量值轉換為 json 值的函數。
因此,您可以為所有數組成員調用此函數(例如,使用https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/map)然后加入它(https://developer .mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/Array/join)并將'['和']'添加到結果字符串
PS:這種方法也適用于您擁有數組數組的情況
實現示例:
var my_json_encode = function(input) {
if(typeof(input) === "string"){
return '"'+input+'"'
}
if(typeof(input) === "number"){
return `${input}`
}
if(Array.isArray(input)) {
const formatedArrayMembers = input.map(value => my_json_encode(value)).join(',');
return `[${formatedArrayMembers}]`;
}
}
添加回答
舉報