0

i am relatively new to stackoverflow and have searched for some time for an answer to my question. I found some links like this one How to split a comma-separated string? but still can't quite understand what I am doing wrong with my short little javascript program.

Anyway here it is. Help would be appreciated.

I basically am trying to create a prompt that asks the user to input 3 numbers seperated by commas, then change that string into an array so that I can multiply the values later on. So far, when i try to console.log this my results are as follows : 1,2 It doesn't print out the third digit(3rd number entered by the user).

var entry = prompt("Triangle side lengths in cm (number,number,number):")
if(entry!=null && entry!="") {
entryArray = entry.split(",");


for (i=0; i<3; i++)
{
entryArray[i] = entry.charAt([i]);
}
}
console.log(entryArray[0] + entryArray[1] + entryArray[2]);
miken32
  • 42,008
  • 16
  • 111
  • 154
mike
  • 3
  • 3

4 Answers4

1

Split creates an array already. So, if you enter 1,2,3, you get an array like this when you split it: ["1", "2", "3"]. In your for loop, you are getting the characters from the original input, not your array. In order to add them, you need to change the input to numbers since they are considered strings. So your for loop should look like this:

for (i=0; i<3; i++)
{
    entryArray[i] = parseFloat(entryArray[i]);
}

overwriting the strings with the digits.

kalley
  • 18,072
  • 2
  • 39
  • 36
0

Try

for (i=0; i<3; i++)
{
    entryArray.push(parseInt(entryArray[i]);
}
Harsha Venkataramu
  • 2,887
  • 1
  • 34
  • 58
0

try this code, i removed your looping which was overwriting the array.

var entry = prompt("Triangle side lengths in cm (number,number,number):");
if(entry!=null && entry!="") {
    entryArray = entry.split(",");
    console.log(entryArray[0] + entryArray[1] + entryArray[2]);
    }
NREZ
  • 942
  • 9
  • 13
DevZer0
  • 13,433
  • 7
  • 27
  • 51
0

You can remove the body of the for。like this:

var entry = prompt("Triangle side lengths in cm (number,number,number):")
console.log(entry);
if(entry!=null && entry!="") {
entryArray = entry.split(",");
console.log(entryArray);
}

console.log(entryArray[0] + entryArray[1] + entryArray[2]);
Deisvn
  • 13
  • 2