问题
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]);
回答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.
回答2:
Try
for (i=0; i<3; i++)
{
entryArray.push(parseInt(entryArray[i]);
}
回答3:
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]);
回答4:
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]);
}
来源:https://stackoverflow.com/questions/17563654/javascript-splitting-by-commas