我现在拥有的是一个函数,返回使用随机数生成器放在一起的2个字符串的数组。这些值将帮助组成一个字符串,如“这是”+ v1 +“,这是”+ v2。 v1和v2是动态创建的字符串。我需要根据字符串的值进行操作。我的问题是我不知道如何对v1和v2所代表的所有不同方式进行有效比较。我想我必须做很多if语句,就像我将在代码中显示的方式一样。我知道有一个更好的方法来进行比较。它是什么?测试动态创建的字符串
//the unit function makes sure that a random letter is returned but also makes sure that
the first letter returned comes before the second letter in the values array
function unit(){
var values = ["a", "b", "c", "d", "e" , "f"];
var value1 = Math.floor(Math.random() * (values.length - 1)) + 1;
var value2 = Math.floor(Math.random() * value1);
if(value1 !== value2){
return [values[value2], values[value1]];
}
}
//pseusodo-code
// i have to do a different operation dependeng on the values of v1 and v2
//bad code
function conversion(v1, v2, num){
if(v1 == "a" && v2 == "b"){
return 16 * num
}
if(v1 == "a" && v2 == "c"){
return 32 * num
}
if(v1 == "a" && v2 == "d"){
return 64 * num
}
if(v1 == "a" && v2 == "e"){
return 256 * num
}
if(v1 == "b" && v2 == "c"){
return 18 * num
}
if(v1 == "b" && v2 == "d"){
return 20 * num
}
if(v1 == "b" && v2 == "e"){
return 64 * num
}
if(v1 == "b" && v2 == "f"){
return 256 * num
}
etc
}
function string(){
u = unit()
v1 = u[0];
v2 = u[1]
return "this is " + v1 + " and this " + v2
}
console.log(string())
// for every 2 a theres 1 b's
//for every 16 a there 1 c
//for every 32 a there is 1 d
//for every 64 a there is 1 e
conversion(v1,v2, 2.5)
console.log(v1, " ", v2)
我dont't知道如果我能做到这一点.the真正的VAR值= [“汤匙”,“FL液量“,”杯“,”品脱“,”夸脱“,”加仑/秒“]。你的答案会帮助我比较每个元素1汤匙是2盎司我将如何分配这些值....等等..我只是在'a:{b:16,c:32,d:64,e :256}, b:{c:18,d:20,e:64,f:256}'我可以继续c:{b:18,d:20,e:64,f:256}比较每一个。我在检查时根据每个值分配值。我必须考虑这个 –
如果它关于单位之间的转换系数,你可以将'因素'对象看作是定义所有单位之间转换系数的二维矩阵。如果转换系数保持不变,那应该是可行的。 – stj