我是否可以缩短此代码?看起来很多余。谢谢!
let sanitizedFirstName = sanitize(firstName).trim()
let sanitizedLastName = sanitize(lastName).trim()
let sanitizedEducationalBackground = sanitize(educationalBackground).trim()
let sanitizedAddress = sanitize(address).trim()
let sanitizedRole = sanitize(role).trim()
let sanitizedEmail = sanitize(email).trim()
let sanitizedPassword = sanitize(password).trim()
let sanitizedFarmAddress = sanitize(farmAddress).trim()
答案 0 :(得分:0)
您可以使用分解。
const [sanitizedFirstName, sanitizedLastName, sanitizedEducationalBackground] = [firstName, lastName, educationalBackground].map(x => sanitize(x).trim())
但是,我仍然建议使用更清晰的变量来读取维护。
示例:
const sanitize = (str = "") => str.replace(/\W+/g, "-");
console.log(sanitize("Test me"));
const [firstName, lastName, fullName] = ["Deepak V", "Vish@@", "Deepak V Visha@@"].map(sanitize)
console.log([firstName, lastName, fullName])
或者您可以创建一个util函数,可以清理整个对象。请参阅下面的示例。
const sanitizeObject = (obj) =>
Object.entries(obj).reduce((m, [key, value]) => {
m[key] = sanitize(value);
return m;
}, {});
const sanitize = (str = "") => str.replace(/\W+/g, "-");
const sanitizeObject = (obj) =>
Object.entries(obj).reduce((m, [key, value]) => {
m[key] = sanitize(value);
return m;
}, {});
const person = {
firstName: "Deepak, R",
lastNam: "V Vis",
address: "356 $hhshshs",
age: 30,
salary: 200,
};
const sanitizedPartial = sanitizeObject({
firstName: person.firstName,
lastNam: person.lastNam,
address: person.address,
});
const updatedPerson = {
...person,
...sanitizedPartial,
};
console.log(updatedPerson);
答案 1 :(得分:-1)
一种选择是将vars放入数组并循环它们:
[firstName, lastName, ..., farmAddress].forEach(funciton (name) {
window['sanitized' + (name.charAt(0).toUpperCase() + name.slice(1))] = sanitize(name).trim()
});