代码风格

Nahida大约 1 分钟

未完成

本页内容尚在补充过程中...

基础

🔨 示例: 以下示例展示了一些基础的代码风格建议,可以让代码更清晰可读。当然,这不是必须的

// 赋值时如果表达式比较长 最好分开写 如果比较短 则可以写在一行
let a = getVal(a, process.env.token);
let b = getVal(b, process.env.token);
let c = 1, d = 2;


// 代码段的开括号位于一行的末尾,而不是另起一行的风格 又称为 K&R 风格
if(condition) {
    console.log('Hi!'); 
    // 尽管大多数情况下换行会被默认认作语句结束 使用分号来结束语句依然是有必要的
}


// 先调用 再声明函数 可以有助于更快理解代码的结构和思路
let result = parseKey(a, b);

function showResult(a, b) {
    // ...
}

函数

较多参数时用一个对象代替

// 无需修改
function pow(x, n) {
    // ...
}
function mergeInfo(name, sex, age, height, weight) {
    // ...
}

// 可以这样写...
function mergeInfo({ name, sex, age, height, weight }) {
    // ...
}


mergeInfo({
    name: 'Jack',
    sex: 'male',
    age: 22,
    height: 178,
    weight: 150
})

异步

.then()代替callback

axios.get("https://api.example.com/async/api/1.0/method")
    .then(data => data.data)
    .then(res => {
        console.log(res);
    })
    .catch(err => {
        console.error(err);
    })

async/await代替.then()

const got = await axios.get("https://api.example.com/async/api/1.0/method");
const headers = got.headers;
const data = got.data;
上次编辑于:
贡献者: Nahida