最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Prompt the user for a string - Stack Overflow

programmeradmin1浏览0评论

I'm trying to write a script that prompts the user for a string containing numbers separated by spaces, and then alerts the minimum value, maximum value, and the sum.

Here is what I have so far:

var prompt = (“Enter a string containing numbers separated by spaces”);

I'm trying to write a script that prompts the user for a string containing numbers separated by spaces, and then alerts the minimum value, maximum value, and the sum.

Here is what I have so far:

var prompt = (“Enter a string containing numbers separated by spaces”);
Share Improve this question edited Oct 16, 2012 at 2:16 coderabbi 2,30116 silver badges18 bronze badges asked Oct 16, 2012 at 1:58 tonkatonka 11 silver badge1 bronze badge 3
  • What, specifically, is your question? – Terry Commented Oct 16, 2012 at 2:02
  • 2 Careful with those curly quotes, you want to use regular quotes "". Writing code in a word processor is not a good idea, use a text editor. – elclanrs Commented Oct 16, 2012 at 2:05
  • how do i alert the code to get the min value, max value, and sum? should i use the split operation? – tonka Commented Oct 16, 2012 at 2:07
Add a ment  | 

3 Answers 3

Reset to default 2
var input = prompt('Enter a string containing numbers separated by spaces').split(' ');
var min = Math.min.apply(Math, input);
var max = Math.max.apply(Math, input);
var sum = 0;
for(var i=0; i<input.length; i++){ 
    var n = parseFloat(input[i], 10); // depending on expected input
    sum += n ? n : 0;  // add if number
}

alert('min: '+min+'\nmax: '+max+'\nsum: '+sum);

==> jsfiddle

Edit:


If you are not sure that only valid input is given you have to check the array manually instead of using Math.min and Math.max, wich could result in NaN

// Some variables we'll be using​
var numbers = "", arr, min, max, sum = 0;

// Don't let them pass without valid input
while ( ! numbers.test(/^(\d+\s?)+$/) ) {
    numbers = prompt( "Enter some numbers, separated by spaces." );
}

// Determine min, max, and the sum
arr = numbers.split(" ");
​min = Math.min.apply(null, arr);
max = Math.max.apply(null, arr);

for ( var i = 0; i < arr.length; i++ ) {
    sum += (+arr[i]);
}

// Output results into console
console.log( min, max, sum );

Fiddle: http://jsfiddle/GUcgj/

var input = prompt("Enter a string containing numbers separated by spaces");​
var ary = input.split(" ");

This would load the input into the array ary. However, you'd need to trim any white space and check for proper input before doing any further processing.

发布评论

评论列表(0)

  1. 暂无评论