javascript 使用过多的“if”语句是否是糟糕的编程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33934703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is using too many 'if' statements bad programming?
提问by OliverRadini
I am curious as to if I am using too many if/else if statements. I am writing a tic-tac-toe program using javascript, and to determine if the computer should block the player I am using about 9 if statements and I use about 9 when determining if there is 3 in a row.
我很好奇我是否使用了过多的 if/else if 语句。我正在使用 javascript 编写井字棋程序,并确定计算机是否应该阻止播放器,我使用了大约 9 个 if 语句,在确定是否连续有 3 个语句时,我使用了大约 9 个。
For example:
例如:
if(r1c1V === xOrO && r1c2V === xOrO && r1c3V === xOrO)
{
is3InARow = true;
}
else if(r2c1V === xOrO && r2c2V === xOrO && r2c3V === xOrO)
{
is3InARow = true;
}
else if(r3c1V === xOrO && r3c2V === xOrO && r3c3V === xOrO)
{
is3InARow = true;
}
.
.
.
.
and so on.
等等。
So my question is, am I using too many if statements? or is there no better way to do this? My friend was telling me that I shouldn't really use that many if statements, but I am not sure if he is true or not, I can understand why in some cases that it would be slower or bad, but I am not sure.
所以我的问题是,我是否使用了太多的 if 语句?或者有没有更好的方法来做到这一点?我的朋友告诉我,我真的不应该使用那么多 if 语句,但我不确定他是否真实,我可以理解为什么在某些情况下它会更慢或更糟糕,但我不确定。
Thanks in advance!!
提前致谢!!
采纳答案by StijnvanGaal
Programming is all about automating processes. You will not hear me say that the way you are doing this is wrong. If it works then it is oke. But of course it would be more beautiful if you could find a way to make it check everything automatically. Like looping through all x cords and just check if all of those are checked. This may not be easier, but it will be more extendable. If you'd ever wish to play a game on a ten by ten grid. then you would only have to say that that is the size of the field. Right now you would need to add all those other lines of code.
编程就是自动化流程。你不会听到我说你这样做的方式是错误的。如果它有效,那么它就可以了。但当然,如果你能找到一种方法让它自动检查一切,那就更漂亮了。就像遍历所有 x 条线,然后检查是否所有这些都被选中。这可能不会更容易,但它会更可扩展。如果您想在十乘十的网格上玩游戏。那么你只需要说那是字段的大小。现在您需要添加所有其他代码行。
回答by OliverRadini
This is rather subjective, so is not really ideal for Stack Overflow.
这是相当主观的,因此对于 Stack Overflow 来说并不是很理想。
What your friend is probably suggesting is that programs which use long if/else statements, nested ifs etc. are sometimes difficult to maintain, and are not always very readable. You can sometimes replace long if statements with a separate function, which can be much easier to maintain.
您的朋友可能建议的是,使用长 if/else 语句、嵌套 if 等的程序有时难以维护,并且并不总是非常易读。有时您可以用单独的函数替换长 if 语句,这样更容易维护。
For instance in tic-tac-toe:
例如在井字游戏中:
function checkRow(rowToCheck){
if (rowToCheck[0] === rowToCheck[1] && rowToCheck[1] === rowToCheck[2]){
return true;
} else {
return false;
}
}
Not to say that is perfect or even good code, but you can see how it would allow you to reduce the number of if statements in your code. It could be factored further:
并不是说这是完美的甚至是好的代码,但是您可以看到它如何让您减少代码中 if 语句的数量。可以进一步考虑:
function checkRow(rowToCheck){
var allMatch = true;
for (var i=0;i<rowToCheck.length && allMatch;i++){
allMatch = rowToCheck[i] === rowToCheck[0];
}
return allMatch;
}
That allows for rows of varying length, and cuts down of the if statements. Anyway I hope that explains some of the ways you can remove if statements.
这允许不同长度的行,并减少 if 语句。无论如何,我希望能解释一些可以删除 if 语句的方法。
Edit
编辑
Further in the future, I'd suggest that there is yet another, better way to check the equality of the elements in a row:
将来,我建议还有另一种更好的方法来检查连续元素的相等性:
const o = 'o'
const x = 'x'
const rows = [
[o, x, x],
[x, x, x],
[o, o, x]
]
const rowIsEqual = row => !row
.some(square => square !== row[0])
const results = rows.map(rowIsEqual)
console.dir(results)
回答by bbsimonbb
In general, yes, "too many" ifs are bad. Any problem can be solved just using ifs, but everything you see around you, functional programming, recursion, object modelling, is there to stop the if's getting out of control and leaving you with sprawling incomprehensible code. You should be more worried about the depth of nested ifs than the length of a sequence. Here's tic-tac-toeon rosetta code, if you want to see real cleverness.
一般来说,是的,“太多”ifs 是不好的。任何问题都可以通过使用 if 来解决,但是你周围看到的一切,函数式编程、递归、对象建模,都可以阻止 if 失去控制,让你留下难以理解的庞大代码。您应该更担心嵌套 ifs 的深度而不是序列的长度。如果您想看到真正的聪明,这里是rosetta 代码的井字游戏。
回答by Bathsheba
There's not hard-and-fast rule. Do bear in mind that &&
and ||
are short-circuttedmeaning that evaluation stops once the result is known. That and the fact that you are able to order the if
statements in any way you please means that you can optimise things by considering frequent comparisons first.
没有硬性规定。请记住,&&
并且||
是短路的,这意味着一旦知道结果,评估就会停止。这一点以及您可以以if
任何方式对语句进行排序的事实意味着您可以通过首先考虑频繁比较来优化事物。
Always do what's clearest, and if performance is crucial, what's fastest.
始终做最清晰的事情,如果性能至关重要,那么什么是最快的。
回答by Micheal Bee
So many apps are built with long if then else statements? Why? Wouldn't a dictionary be better? Look up the keyword and perform the associated action. I'm surprised I can't find a simple python library that does this for multiple back-ends including databases.
这么多应用程序都是用长的 if then else 语句构建的?为什么?字典不是更好吗?查找关键字并执行相关操作。我很惊讶我找不到一个简单的 python 库来为包括数据库在内的多个后端执行此操作。
回答by VishalProgrammer
I guess using too many if- else statements decrease the readability of the program.You can use switch-case statement instead of using if-else statements.Just google switch-case in javascript and you will get many useful links to get an idea about it.
我想使用太多的 if-else 语句会降低程序的可读性。您可以使用 switch-case 语句而不是使用 if-else 语句。只需在 javascript 中使用 google switch-case,您将获得许多有用的链接来了解它。
回答by rjps12
In your scenario, its not bad at all.
You can add return
on your code if it can so that it won't execute other condition... JUST if its possible on your scenario.
在你的场景中,它一点也不差。如果可以return
,您可以添加您的代码,以便它不会执行其他条件......只要在您的场景中可能。
回答by E. van der Spoel
In these cases we use 'Recursion'.
在这些情况下,我们使用“递归”。
To answer your question; if you use to many if statements you are doing something wrong. You can use other methods to get the to goal you want.
回答你的问题;如果您使用许多 if 语句,您就做错了。您可以使用其他方法来实现您想要的目标。
Example: you got a grid of 2,2 (0,1,2 and 0,1,2). So what you should do is create a algorithm that calculates the score. A very popular one is MiniMax.
示例:您有一个 2,2(0,1,2 和 0,1,2)的网格。所以你应该做的是创建一个计算分数的算法。一个非常流行的是MiniMax。