1.早日返回,而不是if ... else

When it comes to conditional statements, you don’t have to always use classic if/switch syntax. It actually depends on the context you’re working on.

对于条件语句,您不必总是使用经典的if / switch语法。 实际上,这取决于您正在处理的上下文。

ES6 gives you more power for writing better conditional statements. It’s shorter and cleaner.

ES6为您编写更好的条件语句提供了更多功能。 它更短更干净。

That’s what I’ll show you in this article — 6 ways to improve conditional statements depending on the context.

这就是我将在本文中介绍的内容-根据上下文改进条件语句的6种方法。

Keep reading.

继续阅读。

1.早日返回,而不是if ... else (1. Returning Early Instead of if…else)

Nested conditions are ugly, hard to control, and easy to generate bugs. A small screen like Macbook 13’’ cannot display full lines of code if you have multiple level nested blocks. You have to scroll horizontally to see the entire code sometimes, which doesn’t satisfy you.

嵌套条件很丑陋,难以控制,并且容易产生错误。 如果您有多个级别的嵌套块,则Macbook 13''这样的小屏幕无法显示完整的代码行。 您有时必须水平滚动才能看到整个代码,这并不令您满意。

const isBabyPet = (pet, age) => {
if (pet) {
if (isPet(pet)) {
console.log(‘It is a pet!’);

if (age < 1) {
console.log(‘It is a baby pet!’);
}
} else {
throw new Error(‘Not a pet!’);
}
} else {
throw new Error(‘Error!’);
}
};

So, how do you flatten the nested conditions? Return early. Specifically, if there’re errors or something invalid, you should return it at the beginning of the function.

那么,如何平整嵌套条件? 早点回来。 具体来说,如果有错误或无效内容,则应在函数开始时将其返回。

const isBabyPet = (pet, age) => {
if (!pet) throw new Error(‘Error!’);
if (!isPet(pet)) throw new Error(‘Not a pet!’);

console.log(‘It is a pet!’); if (age < 1) {
console.log(‘It is a baby pet!’);
}
};

2.使用Array.includes (2. Using Array.includes)

Assume that you need to check if an animal is a pet like below:

假设您需要检查动物是否是宠物,如下所示:

const isPet = animal => {
if (animal === ‘cat’ || animal === ‘dog’) {
return true;
}

return false;
};

If the collection of pets includes just cat and dog, it’s OK. But what if it has more? Like cat, dog, bird, snake. The list goes on. Of course, you can add more || operator to accomplish the task. However, I get a nicer way below:

如果收集的宠物只包括猫和狗,那就可以了。 但是,如果还有更多呢? 像猫,狗,鸟,蛇。 清单继续。 当然,您可以添加更多||。 操作员完成任务。 但是,我在下面有了更好的方法:

const isPet = animal => {
const pets = [‘cat’, ‘dog’, ‘snake’, ‘bird’];

return pets.includes(animal);
};

You see, it’s prettier than using more || operator. So, for multiple conditions like the above, use Array.includes

您会发现,比使用更多||更漂亮 操作员。 因此,对于上述多种情况,请使用Array.includes

3.使用默认功能参数 (3. Using Default Function Parameters)

We usually make sure a parameter is not null or undefined. If it’s null, we need to assign it a default value before using it.

我们通常会确保参数不为null或未定义。 如果为空,则需要在使用前为其分配默认值。

const isBabyPet = (pet, age) => {
if (!pet) pet = ‘cat’;
if (!age) age = 1; if (age < 1) {
// Do something
}
};

Do we actually have to write the first two if statements? No. By using default values, you can remove them.

我们实际上是否必须编写前两个if语句? 否。通过使用默认值,您可以删除它们。

const isBabyPet = (pet = ‘cat’, age = 1) => {
if (age < 1) {
console.log(‘baby’);
}
};

4.使用Array.every (4. Using Array.every)

What if you’re given an array of pets and asked to check whether all the pets have four legs or not?

如果给了您一系列宠物,并要求检查所有宠物是否有四只脚怎么办?

Typically, we will do as below:

通常,我们将执行以下操作:

const pets = [
{ name: ‘cat’, nLegs: 4 },
{ name: ‘snake’, nLegs: 0 },
{ name: ‘dog’, nLegs: 4 },
{ name: ‘bird’, nLegs: 2 }
];const check = (pets) => {
for (let i = 0; i < pets.length; i++) {
if (pets[i].nLegs != 4) {
return false;
}
} return true;
}check(pets); // false

We got a for and an if statement here. It’s not a lots but it’s still great if we can get rid of them. In fact, we can complete the task with only one line:

我们在这里得到了forif语句。 虽然数量不多,但如果我们能摆脱它们,那仍然很棒。 实际上,我们仅需一行即可完成任务:

let areAllFourLegs = pets.every(p => p.nLegs === 4);

A great improvement, isn’t it?

很大的进步,不是吗?

5.使用Array.some (5. Using Array.some)

Let’s change the task a little bit. Now we will check if at least one pet has four legs. It’s time for using Array.some

让我们稍微更改一下任务。 现在,我们将检查至少一只宠物是否有四只脚。 是时候使用Array.some

let check = pets.some(p => p.nLegs === 4);

6.使用索引代替开关 (6. Using Indexing Instead of switch…case)

The switch statement below is about to return the breeds of the given general pet.

下面的switch语句将返回给定普通宠物的品种。

const getBreeds = pet => {
switch (pet) {
case ‘dog’:
return [‘Husky’, ‘Poodle’, ‘Shiba’];
case ‘cat’:
return [‘Korat’, ‘Donskoy’];
case ‘bird’:
return [‘Parakeets’, ‘Canaries’];
default:
return [];
}
};let dogBreeds = getBreeds(‘dog’); //[“Husky”, “Poodle”, “Shiba”]

There’re case…return, case…return, and case…return again. I’m a programmer and also a writer so I find repetition is kind of boring. Take a look at the more cleaner approach below.

case ... returncase ... returncase ... return 。 我既是程序员又是作家,所以我发现重复很无聊。 看看下面更清洁的方法。

const breeds = {
‘dog’: [‘Husky’, ‘Poodle’, ‘Shiba’],
‘cat’: [‘Korat’, ‘Donskoy’],
‘bird’: [‘Parakeets’, ‘Canaries’]
};const getBreeds = pet => {
return breeds[pet] || [];
};let dogBreeds = getBreeds(‘cat’); //[“Korat”, “Donskoy”]

If you’re anything like me, you will love the second approach than the first one.

如果您像我一样,您会喜欢第二种方法而不是第一种方法。

That’s it. Be flexible when working with conditional statements.

而已。 使用条件语句时要灵活一些。

Did I miss any better ways? If so, let me know in the comment below.

我想念更好的方法吗? 如果是这样,请在下面的评论中让我知道。

Hope you enjoy this article.

希望您喜欢这篇文章。

进一步阅读 (Further Reading)

翻译自: https://medium.com/javascript-in-plain-english/6-tips-to-improve-your-conditional-statements-for-better-readability-56256c5a5245

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值