我正在制作一个项目,我将有6个不同的数字,但我希望所有这些都简化了。问题是,当我简化数字时,它需要大约100行。所以制作它6次,就会给我600行代码。
if (money >= 1000 && money <= 999999){
moneyshow = money/1000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" k $";
}
if (money >= 1000000 && money <= 999999999){
moneyshow = money/1000000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" m $";
}
if (money >= 1000000000 && money <= 999999999999){
moneyshow = money/1000000000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" b $";
}
if (money >= 1000000000000 && money <= 999999999999999){
moneyshow = money/1000000000000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" t $";
}
if (money >= 1000000000000000 && money <= 999999999999999999){
moneyshow = money/1000000000000000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" quad $";
}
if (money >= 1000000000000000000 && money <= 999999999999999999999){
moneyshow = money/1000000000000000000;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+" quint $";
}
if (money >= 0 && money <= 999 || money >= 1000000000000000000000) {
moneyshow = money;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+"$";
}
有什么方法可以简化吗?我也需要它,所以我可以一次使用6个或更多的数字。
答案 0 :(得分:0)
在每个if中声明2个变量,将这些变量设置为要除以的数字和要追加的字符串。
var divideBy;
var appendStr;
if (money >= 1000 && money <= 999999)
{
divideBy = 1000;
appendStr = "k $";
}
然后至少你可以这样做一次:
moneyshow = money/ divideBy;
document.getElementById("money").innerHTML = "Money: "+moneyshow.toFixed(2)+ appendStr;
Javascript中变量的优点在于它们不是强类型的。