我应该从函数“getNumber”中找到最小值和最大值。 我需要提示用户停止,如果用户不想停止,将重复执行“getNumber”功能,直到用户要求停止。 当用户决定停止时,它将从用户键入的输入中找到最大值和最小值。我是否可以知道如何将这三个函数tgr链接到调用最大值和最小值?
//prompt to get number
function getNumber() {
var myNumber;
do {
myNumber = Number(prompt("Enter an unsigned base 10 number:"));
} while (myNumber < 0) //loop will run again and again as long as the number is less than zero
return myNumber;
}
//function to find the maximum number in the array
function myMax(myArray) {
var max = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] > max) {
max = myArray[z];
}
}
return max;
}
//function to find the minimum number in the array
function myMin(myArray) {
var min = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] > min) {
min = myArray[z];
}
}
return min;
}
答案 0 :(得分:1)
var numbers = [];
var isStopped = false;
//prompt to get number
function getNumber() {
var input = prompt('Enter an unsigned base 10 number or Input S/s to stop:');
var myNumber = Number(input);
if (input == 'S' || input == 's'){
finish();
}
else if (myNumber > 0 && myNumber < 10){
console.log("input number is: " + myNumber);
numbers.push(myNumber);
}
}
//function to find the maximum number in the array
function myMax(myArray) {
var max = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] > max) {
max = myArray[z];
}
}
return max;
}
function javascript_abort()
{
throw new Error('Programme Ends');
}
//function to find the minimum number in the array
function myMin(myArray) {
var min = myArray[0];
for (var z = 0; z < myArray.length; z++) {
if (myArray[z] < min) {
min = myArray[z];
}
}
return min;
}
function finish(){
isStopped = true;
alert('Max:' + myMax(numbers) + ' Min:' + myMin(numbers));
}
$(document).ready(function() {
while(!isStopped){
getNumber();
}
});
&#13;
<html>
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="app.js"></script>
</head>
<body>
</body>
</html>
&#13;
答案 1 :(得分:1)
function getMinMaxFromUsersInput(){
// User inputted numbers
var numbers = [];
// Get numbers till user ask to stop
do {
numbers.push(getNumber());
} while(confirm("Continue?"));
// Return min and max
return {
min: myMin(numbers),
max: myMax(numbers)
}
}
答案 2 :(得分:0)
一种简单的方法可能是
function getNumber() {
var myNumber;
do myNumber = prompt("Enter an unsigned base 10 number:");
while (myNumber*1 < 0 && myNumber != "exit"); //loop will run again and again as long as the number is less than zero
return myNumber;
}
function getMinMax(a){
return [Math.min.apply(Math,a),Math.max.apply(Math,a)]
}
function doTheLoop(){
var num = getNumber();
num === "exit" ? alert("thanks. bye..!") : (arr.push(num*1),
console.log(arr,getMinMax(arr)),
doTheLoop())
}
var arr = [];
doTheLoop();
在控制台检查结果。