...

View Full Version : JavaScript - New Array via prompt



elresleff
11-19-2010, 04:31 AM
I am new to learning JS and am trying to create an array through a prompt. It seems to work, but I believe it is treating the prompted numbers as strings not numbers. I am parsing the negatives and zeros, and positives and counting them. It doesn't recognize the negative sign.

Here's my js:

function counter()
{
var numArr = new Array(Number(prompt("Please enter and array of numbers, in any order, separated by a comma..." + '\n' +
"In the following format: -2,0,2")));

var positives = 0;
var negatives = 0;
var zeros = 0;

for (var i = 0; i < numArr.length; i++)
{
switch (true) {

case numArr[i] < 0:
negatives++;
break;
case numArr[i] == 0:
zeros++;
break;
case numArr[i] > 0:
positives++;
break;
}
}
alert("You entered:"+ '\n' +
"Number of Negatives: " + negatives + '\n' +
"Number of Zeros: " + zeros + '\n' +
"Number of Positives: " + positives);
}
counter();



Any suggestions?

DrDOS
11-19-2010, 04:56 AM
The values returned by prompts and form elements are strings and you need to apply the functions parseInt or parseFloat to them to convert them to numbers.

glenngv
11-19-2010, 06:27 AM
elresleff is already converting the prompt input to numbers by using Number(). The problem is the prompt is expecting the input to be a comma delimited numbers and he/she is converting the whole string as a number which obviously will not work.

elresleff, you need to split the input to form an array then convert each string to number before the switch statement.



var input = prompt("Please enter and array of numbers, in any order, separated by a comma..." + '\n' +
"In the following format: -2,0,2", "");
var numArr = [];
if (input){
numArr = input.split(',');
}

for (var i = 0; i < numArr.length; i++) {
var num = Number(numArr[i]);
switch (true) {
case num < 0:
negatives++;
break;
case num == 0:
zeros++;
break;
case num > 0:
positives++;
break;
}
}
alert("You entered:"+ '\n' +
"Number of Negatives: " + negatives + '\n' +
"Number of Zeros: " + zeros + '\n' +
"Number of Positives: " + positives);

elresleff
11-19-2010, 06:56 AM
Many thanks Glenn... I do remember seeing the input.split in an example. Thanks for showing it to me in use!

Ed



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum