[英]How to optimize conditional statements in my code
I have a 2D array named extraRank
which holds other users arrays named userA , userB , userC and userD whenever I push them into it: 我有一个名为2D阵列
extraRank
保持名为用户A, 用户B, 用户C和userD其他用户阵列每当我推动它们到其中:
// users arrays:
userA = ["Sara Ree",18, "Doctor", "441", "31"];
userB = ["Marry",18, "Nurse", "41", "1"];
userC = ["John Doe",18, "Woker", "21", "31"];
userD = ["Alex Morph",18, "Musisian", "81", "51"];
// users arrays may be pushed to this array
let extraRank = [];
what I want is an efficient way to do this: 我想要的是一种有效的方法:
first, check which users arrays exist in extraRank
. 首先,检查
extraRank
存在哪些用户数组。
then if for example, userA exist do this: 然后,如果例如userA存在,请执行以下操作:
if extraRank.indexOf(userA) == 0
then assign userA_Index = 10;
如果
extraRank.indexOf(userA) == 0
则指定userA_Index = 10;
if extraRank.indexOf(userA) == 1
then assign userA_Index = 9;
如果
extraRank.indexOf(userA) == 1
则指定userA_Index = 9;
if extraRank.indexOf(userA) == 2
then assign userA_Index = 8;
如果
extraRank.indexOf(userA) == 2
则指定userA_Index = 8;
if extraRank.indexOf(userA) == 3
then assign userA_Index = 7;
如果
extraRank.indexOf(userA) == 3
则分配userA_Index = 7;
I know one way is to this using if statements for each user, but I'm wondering if there is a more efficient way to do it... 我知道一种方法是使用每个用户的if语句 ,但我想知道是否有更有效的方法来做...
If the assignment is linear, as suggested by your example, you can do a simple subtraction: 如果分配是线性的,如您的示例所示,您可以执行简单的减法:
userA_index = 10 - extraRank.indexOf(userA)
If it is more complex, you can create a map object that connects the index to the result, such as: 如果它更复杂,您可以创建一个将索引连接到结果的地图对象,例如:
const mapIndexToOutput = {
0: 10,
1: 9,
2: 8,
3: 7,
...
}
userA_index = mapIndexToOutput[extraRank.indexOf(userA)]
I don't totally understand your requierement, but would a simple substraction do the trick ? 我并不完全理解你的需求,但是这样做会有一个简单的减法吗?
userA_Index = 10 - extraRank.indexOf(userA)
But I'm not sure of what you want to achieve here. 但我不确定你想在这里实现什么。
Edit: You say that you want to optimize for execution time. 编辑:您说您想优化执行时间。 This will be more efficient that a bunch of if.
这将是一堆if的效率更高。 However, I don't think even 10
if
statements are going to be noticeable. 不过,我不认为甚至10
if
语句都将是明显的。 How slow is your code now ? 你的代码现在有多慢? How many
user
do you have ? 你有多少
user
? You migth have other place to optimise first, but it is hard to say without a larger view of your app. 您可以先迁移其他地方进行优化,但如果没有更大的应用视图,很难说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.