<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>【函数重载】编写一个方法,能接收若干数值 和 一个 运算方法,获取若干数值的 运算结果。</title>
<script>
function add(arr) {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
for (var x = 0; x < arr.length; x++) {
sum += arguments[i][x];
}
}
return sum;
}
function multiple(arr) {
var sum = 1;
for (var i = 0; i < arguments.length; i++) {
for (var x = 0; x < arr.length; x++) {
sum *= arguments[i][x];
}
}
return sum;
}
function division(arr) {
var sum = 1;
for (var i = 0; i < arguments.length; i++) {
for (var x = 0; x < arr.length; x++) {
sum /= arguments[i][x];
}
}
return sum;
}
function sole(arr) {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
for (var x = 0; x < arr.length; x++) {
sum -= arguments[i][x];
}
}
return sum;
}
function start(selectOperate, inputNum, add, multiple, division, sole, main) {
var isOk = true;
main(selectOperate, inputNum, add, multiple, division, sole);
}
function main(selectOperate, inputNum, add, multiple, division, sole) {
var a = selectOperate();
var sum = 0;
var doOperateNum = 0;
switch (a) {
case 1:
doOperateNum = inputNum();
sum = add(doOperateNum);
console.log(sum);
break;
case 2:
doOperateNum = inputNum();
sum = sole(doOperateNum);
console.log(sum);
break;
case 3:
doOperateNum = inputNum();
sum = multiple(doOperateNum);
console.log(sum);
break;
case 4:
doOperateNum = inputNum();
sum = division(doOperateNum);
console.log(sum);
default:
break;
}
}
function selectOperate() {
var selecNum = parseInt(prompt('请输入您要进行的操作。1.加法,2.减法,3.乘法,4.除法.5.退出'));
return selecNum;
}
function inputNum() {
var isOk = true;
var arr = [];
var a = 0;
do {
var inputNum = parseFloat(prompt('请输入您要进行计算的值'));
arr[a] = (inputNum);
a++;
if (isNaN(inputNum) || inputNum == null || inputNum == '') {
isOk = false;
arr.pop();
}
} while (isOk);
return arr;
}
start(selectOperate, inputNum, add, multiple, division, sole, main);
</script>
</head>
<body>
</body>
</html>
慕设计2395807
慕移动2103324
相关分类