我的代码:

function calculate(sides) {

  var sides = prompt("Triangle side lengths in cm
  (number,number,number)"); //String will be size of 4

  var nsides = sides.split(" "); //Splits content into array format
  //Convert Array instances to integer values a,b,c

  for(var loop=0;loop<=nsides.length;loop++)   {
  if(nsides[loop]!=",")
  a = nsides[loop];

  if(nsides[loop]!=",")
  b = nsides[loop];

  if(nsides[loop]!=",")
  c= nsides[loop];
  } //End for

  //Area Calculation
  var s = (a+b+c)*0.5 ; //represents the semiperimeter
  var area = Math.sqrt(s*(s-a)*s(s-b)*(s-c)) //area calculation

      //Result
  sides = alert("The triangle's area is " + area + " square cm");


}   //End function

 //Main calculate(length);

我希望将a、b和c设置为整数;但是为了这样做,我必须遍历数组(我首先将它从字符串转换为数组)
稍后我将添加一些标准验证;到目前为止,我似乎无法将输入的字符串中的值放入3个独立的整数中,即b和c。
除此之外,我还有更好的办法吗?
谢谢。

最佳答案

也许我误解了你的问题,但这就是你要找的吗?

var sides = prompt("Triangle side lengths in cm (number,number,number)");
var nsides = sides.split(",");
var a = +nsides[0];
var b = +nsides[1];
var c = +nsides[2];

//Area Calculation
//...

注意使用+将数组中的字符串强制为数字。

10-07 20:10