1

提升你的技能:编写干净高效的 JavaScript 的 7 个技巧

 1 year ago
source link: https://blog.51cto.com/u_1213352/5996670
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

提升你的技能:编写干净高效的 JavaScript 的 7 个技巧

精选 原创

编写干净的代码对每个开发人员来说都是必不可少的,因为它使代码易于阅读、理解和维护。 干净的代码使团队中每个人的生活更轻松,您的代码更不容易出错,并且更容易添加新功能。 在本教程中,我将介绍 7 个技巧,以便您可以立即编写更具可读性的代码。


使用正确的缩进

使用适当的缩进不仅使代码更易于阅读,还有助于阐明代码的结构。 在整个代码中使用一致的缩进以提高可读性并使其更易于理解。

function getTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
return total;
}
function getTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
total += items[i].price;
}
return total;
}

使用描述性和有意义的变量名

当您决定添加新变量时,请帮自己一个忙,多花几秒钟,尤其是当它们不仅仅是循环计数器或类似的东西时。

使用描述性的和有意义的变量名可以大大提高代码的可读性。 另外,避免使用不必要的缩写,因为您肯定会在提供智能的 IDE 中编写代码,这样您就不需要每次都输入整个变量名。

let a = 'John';
let b = 'Doe';
let c = a + b;
console.log(c);
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + lastName;
console.log(fullName);

使用注释并大量使用它们。 注释是您在代码中与未来的自己交谈的唯一方式,因此请善待自己并解释所有值得注释的内容。 有时,它只是一个需要说明的常量,有时它是一个完整的函数。

只要确保您在教授编程时不发表评论即可。 每个开发人员都应该知道语法,注释的作用是阐明代码的逻辑。

function movingAverage(arr, windowSize) {
let movingAverages = [];
for (let i = 0; i < arr.length; i++) {
let start = i - Math.floor(windowSize / 2);
let end = i + Math.ceil(windowSize / 2);
if (start < 0) {
start = 0;
}
if (end > arr.length) {
end = arr.length;
}
let sum = 0;
for (let j = start; j < end; j++) {
sum += arr[j];
}
let avg = sum / windowSize;
movingAverages.push(avg);
}
return movingAverages;
}
function movingAverage(arr, windowSize) {
// 初始化一个数组来保存移动平均线
let movingAverages = [];

// 循环遍历数字数组
for (let i = 0; i < arr.length; i++) {
// 计算当前窗口的开始和结束索引
let start = i - Math.floor(windowSize / 2);
let end = i + Math.ceil(windowSize / 2);
// 确保起始索引不为负
if (start < 0) {
start = 0;
}
// 确保结束索引不超过数组的末尾
if (end > arr.length) {
end = arr.length;
}
// 计算当前窗口数字的总和
let sum = 0;
for (let j = start; j < end; j++) {
sum += arr[j];
}
// 计算当前窗口数字的平均值
let avg = sum / windowSize;
// 将平均值添加到移动平均线数组
movingAverages.push(avg);
}
// 返回移动平均线数组
return movingAverages;
}

避免深度嵌套

阅读和理解深层嵌套的代码确实很困难,因此请尽量通过将代码分成更小、更易于管理的块来避免这种情况,或者使用更好的方法来实现相同的逻辑。

function getTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
if (items[i].category === 'clothing') {
if (items[i].color === 'red') {
total += items[i].price;
}
}
}
return total;
}
function getTotal(items) {
let total = 0;
for (let i = 0; i < items.length; i++) {
if (items[i].category === 'clothing' && items[i].color === 'red') {
total += items[i].price;
}
}
return total;
}

限制函数参数

限制传递给函数的参数数量。 这个技巧不是关于不将函数需要的参数传递给它们,而是关于如何定义和组织它们。

function calculateTotal(items, taxRate, discountAmount, shippingCost, freeShippingThreshold) {
// Do something with the parameters
}
function calculateTotal(items, {taxRate, discountAmount, shippingCost, freeShippingThreshold}) {
// Do something with the parameters
}

使用较小的函数

这篇文章更多的是关于编写干净的代码,我想避免将它与 SOLID 原则等概念混在一起,所以请从可读性的角度来看这篇文章。

不要将所有内容都放在一个函数中,而是尝试将其分解成更容易理解和调试的更小的部分。

function processData(data) {
let results = [];
for (let i = 0; i < data.length; i++) {
if (data[i].type === 'A') {
results.push(processTypeA(data[i]));
} else if (data[i].type === 'B') {
results.push(processTypeB(data[i]));
} else if (data[i].type === 'C') {
results.push(processTypeC(data[i]));
}
}
return results;
}

function processTypeA(item) {
// Do something with item of type A
}

function processTypeB(item) {
// Do something with item of type B
}

function processTypeC(item) {
// Do something with item of type C
}
function processData(data) {
let results = [];
for (let i = 0; i < data.length; i++) {
results.push(processItem(data[i]));
}
return results;
}

function processItem(item) {
if (item.type === 'A') {
// Do something with item of type A
} else if (item.type === 'B') {
// Do something with item of type B
} else if (item.type === 'C') {
// Do something with item of type C
}
}

使用较短的行和空行

将您的代码分成较短的行并使用空行来分隔逻辑块,可以使您的代码更易于阅读和理解。 尤其是有时您可能会想使用在博客上找到的一些很酷的技巧来在一行中执行某些操作,但通常它们只会降低您的代码的可读性。

function add(a, b) { return a + b; }
let [taxRate, discountAmount, shippingCost, freeShippingThreshold] = [99, 0, 0, 0;
function add(a, b) {
return a + b;
}

let taxRate = 99;
let discountAmount = 0;
let shippingCost = 0;
let freeShippingThreshold = 0;

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK