2015-02-01 4 views
0

Я пишу небольшое приложение для ввода пользователем имени книги, а затем его цены, значения значений для массива, вывод имени книги и стоимости на страницу, а затем отобразить общее количество.Проблема с добавлением значений из массива

проблема я имею с общим, например:

Если я пишу 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; 
} 
+0

Похоже, вам нужно сотрудничество nvert ваши строки к номерам http://stackoverflow.com/questions/1133770/how-do-i-convert-a-string-into-an-integer-in-javascript – robobobobo

ответ

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

prompt возвращает строку, и когда вы добавляете число (0) и строку ("2"), вы получаете строку ("02"). Вы должны бросить на номер здесь:

price.push(+bookPrice); 

(унарный + бросает в ряд)

+0

работает отлично! благодаря! Я не знал, что это так просто, ни одна из статей, которые я прочитал, тоже не сказала. Спасибо чувак! – SkullDev

0

Вы добавляете строк не является Numbers. Например:

"Hello " + "World"; 

Будет выдавать «Hello World».

"10" + "20"; 

Выведет "1020"

Вместо этого вы должны преобразовать строку в число

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

будет Ouput 30

Чтобы применить это к коду:

price.push(Number(bookPrice));