用逗号分割Javascript
我对stackoverflow比较陌生,并且已经搜寻了一段时间来寻找我的问题的答案。我发现了一些这样的链接如何分割逗号分隔的字符串?
,但仍然无法完全理解我的简短JavaScript小程序在做什么。
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.
我基本上是在尝试创建一个提示,要求用户输入用逗号分隔的3个数字,然后将该字符串更改为数组,以便我以后可以将值相乘。到目前为止,当我尝试console.log时,我的结果如下:1,2
它没有打印出第三位数字(用户输入的第三位数字)。
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]);
Split已创建一个数组。因此,如果输入1,2,3,则在拆分时会得到如下数组: [ 1, 2, 3]
。在 for
循环中,您从原始输入而不是数组中获取字符。为了添加它们,您需要将输入更改为数字,因为它们被视为字符串。因此,您的 for
循环应如下所示:
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]);
}
用数字覆盖字符串。