javascript中输入的总和

javascript中输入的总和,javascript,arrays,sum,Javascript,Arrays,Sum,我试图找到用户在弹出窗口中输入的总价格,并显示总价格。我是否需要在输出下添加另一行? 我试图沿着outMsg添加总数,但没有成功。 谢谢 数组02 图书销售 在循环中,您需要对total变量进行计数,如下所示: for(var i = 0; i < arraySize; i++) { total += parseFloat(bookPrice[i]); // Whatever else you need to do... } for(变量i=0;i

我试图找到用户在弹出窗口中输入的总价格,并显示总价格。我是否需要在输出下添加另一行? 我试图沿着outMsg添加总数,但没有成功。 谢谢


数组02
图书销售


在循环中,您需要对
total
变量进行计数,如下所示:

for(var i = 0; i < arraySize; i++)
{
    total += parseFloat(bookPrice[i]);
    // Whatever else you need to do...
}
for(变量i=0;i
计算
总数
并使用
parseInt
(或
parseFloat
)进行类型转换

函数书(){
//定义变量
var arraySize=2;
var bookName=新数组(arraySize);
var bookPrice=新数组(arraySize);
var合计=0;
var outMsg=“”;
对于(变量i=0;i“+total+”
”;//在窗口上显示反斜杠n(\n) //警报(outMsg) document.getElementById(“Books”).innerHTML=outMsg; } }

数组02
图书销售


首先,您需要通过使用
parseInt()
并将其添加到for循环中的
total
变量来计算total。然后,您只需要计算希望附加的响应,然后将第二个for循环之外的响应附加到所需的元素。 数组02


图书销售


我认为这是我犯的错误,有时我会漏掉一些括号。谢谢你指出。你用什么文本编辑器来开发这个?许多文本编辑器都有过梁可用。linter是在每次保存时检查语法并告诉您是否出错的工具(例如,我在OS X上使用了一个缺少的
括号。谢谢shivgre,不知怎的,在修改代码时,我注意到即使在第二本书名上,数字也被打印出来了。我需要重新检查我的代码,谢谢你的帮助。)help@DanPhelps欢迎:-)可以吗?我可能也按了much@DanPhelps不,它仍然没有完成,试着只点击一次向上按钮
for(var i = 0; i < arraySize; i++)
{
    total += parseFloat(bookPrice[i]);
    // Whatever else you need to do...
}
  <form action="">

<p>BOOK SALE</p>
<p id="Books"</p>
<input type="button" value="Start" onClick="Books();" >

</form>  
<body>
<script>
    function Books()
    {
            //define variables 
            var  arraySize = 2;
            var bookName = new Array(arraySize);
            var bookPrice = new Array(arraySize);
            var total = 0;

            var outMsg      = "";

            for(var i = 0; i < arraySize; i++)    
            {
                    bookName[i] = prompt('Enter Book Name:  ', "");
                    bookPrice[i] = prompt('Enter the Price: ',0);
                    total += parseInt(bookPrice[i]);
            }
            console.info("TOTAL PRICE:" + total );//this will print in blue color the total price in your console
            for(var i = 0; i < arraySize; i++)    
            {
                outMsg = outMsg + bookName[i] + " " + bookPrice[i] + "</br>" + total; // put backslash n (\n) to show on window
                //alert(outMsg)
                console.info("OutMsg :" + outMsg);// use console.log(),console.info(), console.warn(), instead of the old school alert() along with the browser/firebug console.
                 //You should move this line out of for loop because you only have one element in which you wish to append your output
                //document.getElementById("Books").innerHTML = outMsg;

            }
            document.getElementById("Books").innerHTML = outMsg;
    }
    </script>
</body>
<html>