gpt4 book ai didi

javascript - 测试动态创建的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:22:48 26 4
gpt4 key购买 nike

我现在拥有的是一个函数,它返回一个由 2 个字符串组成的数组,这些字符串是使用随机数生成器组合在一起的。这些值将有助于组成一个字符串,如“this is”+ v1 +“and this is”+ 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)

最佳答案

您不能创建一个包含所有乘法因子的查找对象吗?把它想象成一个二维表:

var factors = {
a: { b: 16, c: 32, d: 64, e: 256 },
b: { c: 18, d: 20, e: 64, f: 256 }
};

那么转换函数就变成了:

function conversion (v1, v2, num) {
if (! factors.hasOwnProperty(v1)) {
throw "no conversion defined on first level for value " + v1;
}
if (! factors[v1].hasOwnProperty(v2)) {
throw "no conversion defined on second level for value " + v1 + ", " + v2;
}
return num * factors[v1][v2];
}

请注意,虽然我在上面的 factors 对象中手动编码了值,但它的值也可以通过编程方式设置。

关于javascript - 测试动态创建的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901641/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com