从数组中添加值的问题

时间:2015-02-01 17:55:31

标签: javascript arrays subtotal

我正在为用户编写一个小应用程序,输入一本书的名称,然后输入它的价格,将这些值的值推送到一个数组,输出书名和费用到页面然后显示总数。

我遇到的问题是总数,例如:

如果我写2作为每个值的值,那么“totalOutput”就像我期望的那样说022222而不是10,我已经尝试了一些不同的东西,并在这里阅读了一些文章,但没有找到任何提供很多帮助或有用。

这些是我遇到问题的确切行:

//go over each item in price and add up the total
        price.forEach(function addNumber(value) {
            total += value;
        });

//write the total
    totalOutput.innerHTML = "the total value of the books is " + total;
}

并且你需要它 - 这是我的完整javascript代码:

//Book shop task
function trackBooks() {

    //target the output ul and store in a variable
    var output = document.getElementById("booksOutput");

    //Setup the two arrays to hold the book names and their prices.
    var books = [];
    var price = [];

    //declare a variable for working out the total
    var total = 0;

    //target the total output
    var totalOutput = document.getElementById("totalOutput");

    //set up a counter for the loop
    var x = 0;

    //setup the loop for entering the names of the books and their prices, for the sample, I have set the loop to run 5 times as stated in the pseudo code
    for (var i = 0; i < 5; i++) {

        //add one to the counter on each loop
        x = x + 1;

        //declare a variable to ask the user for the book name and the cost and push those values to their arrays we created above
        var bookName = prompt("enter book name number " + x);
        books.push(bookName);
        var bookPrice = prompt("how much does book number " + x + " cost?");
        price.push(bookPrice);

        //create a variable to create new li tags on output 
        var newLi = document.createElement("li");

        //add the required info to the new link
        newLi.innerHTML = "book " + x + ": " + "<strong>" + books[i] + "</strong>" + " costs " + "<strong>" + price[i] + "</strong>";

        //write out the name and price to the page
        output.appendChild(newLi);

    }

    //go over each item in price and add up the total
    price.forEach(function addNumber(value) {
        total += value;
    });

    //write the total
    totalOutput.innerHTML = "the total value of the books is " + total;
}

2 个答案:

答案 0 :(得分:0)

    var bookPrice = prompt("how much does book number " + x + " cost?");
    price.push(bookPrice);

prompt返回一个字符串,当您添加数字(0)和字符串("2")时,您会得到一个字符串("02")。你应该在这里输入数字:

price.push(+bookPrice);

(一元+投射到数字)

答案 1 :(得分:0)

您正在添加字符串而不是数字。例如:

"Hello " + "World";

将输出“Hello World”。

"10" + "20";

将输出“1020”

相反,您必须将String转换为数字

Number("10") + Number("20");

将输出30

将此应用于您的代码:

price.push(Number(bookPrice));