JSON.stringfy(): 将 JS 对象转化为 JSON 字符串。
const obj = { name: 'John', age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // {"name":"John","age":30}
JSON.parse(): 将 JSON 字符串转化为 JS 对象,键值都必须使用双引号包裹。
const jsonString = '{"name":"John","age":30}';
const obj = JSON.parse(jsonString);
console.log(obj); // { name: 'John', age: 30 }
常用场景:
封装:
export class LocalStorage {
static read = (key: string) => {
const readObj = window?.localStorage?.getItem(key);
try {
return JSON.parse(readObj);
} catch (err) {
console.log(`READ from localStorage "${key}" - `, err);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
static write = (key: string, value: any) => {
window?.localStorage?.setItem(key, JSON.stringify(value));
};
static remove = (key: string) => {
window?.localStorage?.removeItem(key);
};
}
封装作用:
使用:
export enum EStorageKey {
JOINED_TOUR = 'JOINED_TOUR',
}
const storageJoinedTours = LocalStorage.read(EStorageKey.JOINED_TOUR);