在 JavaScript 中使用“return"而不是“else" [英] Using 'return' instead of 'else' in JavaScript

查看:29
本文介绍了在 JavaScript 中使用“return"而不是“else"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个需要一些非常复杂的 JavaScript 处理的项目.这包括在很多地方嵌套了很多if-else.我通常通过阅读有关 Stack Overflow 的其他技巧来尽可能地优化 JavaScript 代码,但我想知道以下两个构造是否会单独在速度方面产生任何影响:

I am working on a project which requires some pretty intricate JavaScript processing. This includes a lot of nested if-elses in quite a few places. I have generally taken care to optimise JavaScript code as much as possible by reading the other tips on Stack Overflow, but I am wondering if the following two constructs would make any difference in terms of speed alone:

if(some_condition) {
    // process
    return ;
}

// Continue the else condition here

对比

if(some_condition) {
    // Process
}

else {
   // The 'else' condition...
}

推荐答案

我总是采用第一种方法.更容易阅读,更少的缩进.至于执行速度,这将取决于实现,但我希望它们都是相同的.

I always go with the first method. Easier to read, and less indentation. As far as execution speed, this will depend on the implementation, but I would expect them both to be identical.

这篇关于在 JavaScript 中使用“return"而不是“else"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆