目录
JSON序列化
JSON反序列化
序列化和反序列化转换
深拷贝
JSON.parse接受参数类型错误导致抛出异常
当有子元素的时候,设置父元素样式的方式
防抖问题
JSON序列化
const obj = {name: "John",age: 30,city: "New York",};// 基本用法,将对象转换为 JSON 字符串const jsonString = JSON.stringify(obj);console.log(jsonString);// 使用 replacer 函数进行自定义转换const replacer = (key, value) => {if (typeof value === "number" && value > 25) {return value + 1;}return value;};const jsonStringWithReplacer = JSON.stringify(obj, replacer);console.log(jsonStringWithReplacer);// 使用 space 参数来控制缩进const jsonStringWithIndentation = JSON.stringify(obj, null, 4);console.log(jsonStringWithIndentation);obj.toJSON=function(){return {fullName:this.name,yearsOld:this.age,location:this.city}}const jsonString1= JSON.stringify(obj);console.log(jsonString1);
JSON反序列化
// 假设我们有一个JSON格式的字符串const jsonString ='{"name": "Alice", "age": 25, "isStudent": true, "courses": ["Math", "Science"], "address": {"city": "New York", "zip": "10001"}}';// 使用JSON.parse将JSON字符串反序列化为JavaScript对象const parsedObject = JSON.parse(jsonString, (key, value) => {console.log(`Key: ${key}, Value: ${value}`);// 如果值是字符串类型,并且可以转换为数字,则将其转换为数字if (typeof value === "string" && !isNaN(value)) {return Number(value);}// 返回原始值return value;});// 输出反序列化后的对象console.log(parsedObject);
序列化和反序列化转换
// 定义一个对象const person = {name: "Alice",age: 25,hobbies: ["reading", "swimming"],};// 将对象序列化为 JSON 字符串const jsonString = JSON.stringify(person);// 使用 JSON.parse() 进行反序列化const deserializedPerson = JSON.parse(jsonString);// 打印原始对象、JSON 字符串和反序列化后的对象console.log("原始对象:", person);console.log("JSON 字符串:", jsonString);console.log("反序列化后的对象:", deserializedPerson);
深拷贝
const obj = {name: "John",age: 30,address: {street: "123 Main St",city: "New York",state: "NY",},};const deepCopy = JSON.parse(JSON.stringify(obj));// 修改原始对象obj.name = "Jane";obj.address.city = "Los Angeles";// 打印原始对象和深拷贝对象console.log("原始对象:", obj);console.log("深拷贝对象:", deepCopy);
JSON.parse接受参数类型错误导致抛出异常
export const filterLockAndNoExistList = (oldParam: string, authInfo: AuthInfo): string => {if (isNil(oldParam) || isNil(authInfo)) return '';const oldParamArray = oldParam?.split(',') || [];// lockList为大整型的数组,用BigInt解决精度损失问题const lockList = JSON.parse(authInfo?.lockList || '[]').map((i: number) => BigInt(i)+'');const noExistList = JSON.parse(authInfo?.noExistList || '[]').map((i: number) => BigInt(i)+'');// 过滤掉存在于 lockList 或 noExistList 中的元素const filteredArray = oldParamArray.filter(id =>!lockList.includes(id) && !noExistList.includes(id));return filteredArray.join(',');
};
const lockList = (Array.isArray(authInfo?.lockList) ? authInfo.lockList : JSON.parse(authInfo?.lockList || '[]')).map((i: number) => BigInt(i) + '');
当有子元素的时候,设置父元素样式的方式
.poppy-spin-container {// 默认样式min-width: 200px;// 当子元素中存在 .bill-data-empty 时&:has(.bill-data-empty) {min-width: 300px;}
}
防抖问题