(资料图)
在本文中,我们将分享一些可以帮助你编写干净的 JavaScript 代码的技巧。无论你是初级职位还是高级职位,它都一定会帮助你提高实践水平。
在本文中,我们将分享一些可以帮助你编写干净的 JavaScript 代码的技巧。无论你是初级职位还是高级职位,它都一定会帮助你提高实践水平。
// Badconst firstName = user.firstName;const lastName = user.lastName;// Goodconst { firstName, lastName } = user;
// Badconst newArray = [...oldArray];// Goodconst newArray = [...oldArray];
// Badfunction updateArray(arr) { arr.push(4);}// Goodfunction updateArray(arr) { const newArr = [...arr, 4]; return newArr;}
// Badconst fullName = firstName + " " + lastName;// Goodconst fullName = `${firstName} ${lastName}`;
// Badlet counter = 0;// Goodconst counter = 0;
// Badfunction getUserInfo(user) { const name = user.name; const age = user.age;}// Goodfunction getUserInfo({ name, age }) { // Code to use name and age}
// Badif (condition1) { if (condition2) { if (condition3) { // Code } }}// Goodif (condition1 && condition2 && condition3) { // Code}
// Badlet sum = 0;for (let i = 0; i < numbers.length; i++) { sum += numbers[i];}// Goodconst sum = numbers.reduce((acc, curr) => acc + curr, 0);
// Badfunction calculateTotal(price, quantity) { if (price && quantity) { // Code to calculate total return total; }}// Goodfunction calculateTotal(price, quantity) { if (!price || !quantity) { return; } // Code to calculate total return total;}
// Bad// Increment the counter by 1counter++;// Good/** * Increments the counter by 1. */counter++;
const counter = (() => { let count = 0; return { increment: () => { count++; }, getCount: () => { return count; }, };})();
const memoizedFunction = (() => { const cache = {}; return (arg) => { if (cache[arg]) { return cache[arg]; } const result = expensiveOperation(arg); cache[arg] = result; return result; };})();
// Badconst person = { name: "John", age: 30,};person.age = 31;// Goodconst person = { name: "John", age: 30,};const updatedPerson = { ...person, age: 31 };
// Badfunction processUserData(userData) { // complex logic...}// Goodfunction validateUserData(userData) { // validation logic...}function sanitizeUserData(userData) { // sanitization logic...}function processUserData(userData) { validateUserData(userData); sanitizeUserData(userData); // remaining logic...}
// Badfunction calculateAreaAndPerimeter(radius) { const area = Math.PI * radius * radius; const perimeter = 2 * Math.PI * radius; console.log(`Area: ${area}, Perimeter: ${perimeter}`);}// Goodfunction calculateArea(radius) { return Math.PI * radius * radius;}function calculatePerimeter(radius) { return 2 * Math.PI * radius;}const area = calculateArea(5);const perimeter = calculatePerimeter(5);console.log(`Area: ${area}, Perimeter: ${perimeter}`);
以上就是我今天与你分享的15个关于写出更好JS的小技巧,希望对你有用。
关键词: