// 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(null, 10);
const price2 = calculatediscount(null, 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;
通过遵循这些标准,您可以确保您的 javascript 代码干净、可维护且高效。