// Good const userAge = 25; function calculateTotalPrice(items) { ... } // Bad const a = 25; function calc(items) { ... }
const userAge = 25; function calculateTotalPrice(items) { ... } class UserProfile { ... }
// Good function calculateDiscount(price, discount) { ... } const price1 = calculateDiscount(100, 10); const price2 = calculateDiscount(200, 20); // Bad const price1 = 100 - 10; const price2 = 200 - 20;
async function fetchData() { try { const response = await fetch('api/url'); const data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); } }
function getUserAge(user) { if (!user || !user.age) { return 'Age not available'; } return user.age; }
if (condition) { doSomething(); } else { doSomethingElse(); }
// utils.js export function calculateDiscount(price, discount) { ... } // main.js import { calculateDiscount } from './utils.js';
// ui.js function updateUI(data) { ... } // data.js async function fetchData() { ... } // main.js import { updateUI } from './ui.js'; import { fetchData } from './data.js';
'use strict';
const MAX_USERS = 100;
// Good (function() { const localVariable = 'This is local'; })(); // Bad var globalVariable = 'This is global';
/** * Calculates the total price after applying a discount. * @param {number} price - The original price. * @param {number} discount - The discount to apply. * @returns {number} - The total price after discount. */ function calculateTotalPrice(price, discount) { ... }
// Good async function fetchData() { try { const response = await fetch('api/url'); const data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); } } // Bad function fetchData(callback) { fetch('api/url') .then(response => response.json()) .then(data => callback(data)) .catch(error => console.error('Error fetching data:', error)); }
// Good const vehicle = { make: 'Toyota', model: 'Camry' }; const { make, model } = vehicle; // Bad const vehicleMake = vehicle.make; const vehicleModel = vehicle.model;
Dengan mengikut piawaian ini, anda boleh memastikan kod JavaScript anda bersih, boleh diselenggara dan cekap.
Atas ialah kandungan terperinci Piawaian Pengekodan Umum JavaScript.. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!