我将多个用户输入存储在一个名为 inputObj 的对象中,然后需要对这些属性全部进行排名(满分 100)(附件是对一个属性进行排名的当前方法),需要对最多 20 个属性执行此操作,所以目前这是一种我经常重复的方法。
数学一切正常,我得到了想要的输出,但需要一种更简洁的方法来做到这一点,有建议吗?
主要问题是每个属性的数学操作都会改变,因此适用于所有属性的通用函数将不起作用
谢谢
if (inputObj.dyAGE <=5) {
inputObj.dyAGE *= 5.5;
}
else if (inputObj.dyAGE<=7) {
inputObj.dyAGE -= 5;
inputObj.dyAGE *= 16.5;
inputObj.dyAGE += 33;
}
else if(inputObj.dyAGE<=11) {
inputObj.dyAGE -= 7;
inputObj.dyAGE *= 8.25;
inputObj.dyAGE += 66;
}
else if (inputObj.dyAGE<=16) {
inputObj.dyAGE -= 17;
inputObj.dyAGE = -inputObj.dyAGE;
inputObj.dyAGE *= 6.6;
inputObj.dyAGE += 66;
}
else if(inputObj.dyAGE <= 19) {
inputObj.dyAGE -= 20;
inputObj.dyAGE = -inputObj.dyAGE;
inputObj.dyAGE *= 11;
inputObj.dyAGE += 33
}
else if (inputObj.dyAGE <= 30) {
inputObj.dyAGE-31;
inputObj.dyAGE = -inputObj.dyAGE;
inputObj.dyAGE *= 3;
};
最佳答案
您可以使用函数:
inputObj.dyAGE = convert_AGE(inputObj.dyAGE)
function convert_AGE(x) {
if (x <= 5)
return x * 5.5;
if (x <= 7)
return (x - 5) * 16.5 + 33;
etc
您还可以将一系列赋值 (inputObj.dyAGE=...
) 转换为表达式,这样
inputObj.dyAGE -= 17;
inputObj.dyAGE = -inputObj.dyAGE;
inputObj.dyAGE *= 6.6;
inputObj.dyAGE += 66;
变成这样
(17 - x) * 6.6 + 66
甚至
178.2 - 6.6 * x
当然,您可以为每个属性使用不同的函数,例如
inputObj.dyAGE = convert_AGE(inputObj.dyAGE)
inputObj.dyXYZ = convert_XYZ(inputObj.dyXYZ)
或者通过创建函数散列来自动执行此操作:
convertors = {
'dyAGE': function(x) { code to convert age },
'dyXYZ': function(x) { code to convert xyz },
etc
}
然后一次性转换所有属性
for (var prop in input)
if (prop in convertors)
input.prop = convertors[prop](input.prop);
关于javascript - 使用 if 语句 javascript 进行数字操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9429485/