优化后的代码:
<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title></head><style>#show {width: 100%;}textarea {width: 100%;height: 20rem;outline: none;overflow: none;}</style><body><div class="body"><input type="number" id="num"><button onclick="calculate()">开始计算</button><div id="show"></div></div></body></html>
<script>
var x, y, m, j, arr, temp, len, temp1, stime, ptime, newtemp, i, isnext = false;
//点击开始计算
function calculate() {
//输入的数字
var n = document.getElementById("num").value;
//开始计算时间
var StartTime = new Date().getTime();
inputNum(n).then(function(res) {
var result = res;
//数组反转
result.reverse();
//去除','
result = result.toString().replace(/,/g, '');
//结束时间
var stopTime = new Date().getTime();
//打印输出
document.getElementById("show").innerHTML = "<h2>计算结果为:</h2>" + "<textarea>" + result.toString() +
"</textarea>" + "<br/>" + "<span>总用时:</span>" + (stopTime - StartTime) / 1000 +
"秒";
})
}
//
async function inputNum(n) {
if (n <= 1) {
alert("输入的数不能小于1");
return false;
}
//数字转为数组
var temp = n.split("");
//数组反转
temp.reverse();
for (m = n; m > 0; m--) {
//定义新数组长度与temp一致
temp1 = new Array(temp.length);
//计算前后两位相乘后的结果
await caculateAfter(m, temp, temp1);
//计算进位
temp = this.roundUp(temp1);
//计算至最后一位时返回
if (m == 2) {
return temp;
}
}
return temp;
}
//计算前后两位相乘后的结果,采用递归函数
function caculateAfter(n, temp, temp1) {
const testFun = function(i) {
temp1[i] = parseInt(temp[i]) * (n - 1);
if (i == temp.length - 1) {
return;
}
i++;
testFun(i);
}
testFun(0)
}
/**
* 计算进位
* @param {Object} temp
*/
function roundUp(temp) {
newtemp = new Array(0);
for (i = 0; i <= temp.length - 1; i = i + 1) {
if (temp[i] / 10 >= 1) {
if (i == temp.length - 1) {
if (temp[i] / 10 / 10 >= 1) {
temp.length = temp.length + 1;
temp[temp.length - 1] = parseInt(temp[i] / 10);
newtemp = newtemp.concat(temp[i] % 10);
} else {
newtemp = newtemp.concat(temp[i] % 10, parseInt(temp[i] / 10));
}
} else {
newtemp = newtemp.concat(temp[i] % 10);
temp[i + 1] = parseInt(temp[i] / 10 + temp[i + 1]);
}
} else {
newtemp = newtemp.concat(temp[i]);
}
}
return newtemp.map(String);
}
</script>
看完了,点个关注再走呗!