从数组中添加值的问题
Posted
技术标签:
【中文标题】从数组中添加值的问题【英文标题】:issue with adding values from array 【发布时间】:2015-02-01 17:55:31 【问题描述】:我正在编写一个小应用程序,让用户输入书名和价格,将这些值推送到数组中,将书名和成本输出到页面,然后显示总数。
我遇到的问题是总数,例如:
如果我写 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;
【问题讨论】:
看来您需要将字符串转换为数字***.com/questions/1133770/… 【参考方案1】: var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
prompt
返回一个字符串,当你添加一个数字 (0
) 和一个字符串 ("2"
) 时,你得到一个字符串 ("02"
)。您应该在此处转换为数字:
price.push(+bookPrice);
(一元 +
转换为数字)
【讨论】:
现在完美运行!谢谢!我不知道它这么简单,我读过的文章也没有说这个。谢谢大佬!【参考方案2】:您添加的是字符串而不是数字。例如:
"Hello " + "World";
将输出“Hello World”。
"10" + "20";
将输出“1020”
您必须将字符串转换为数字
Number("10") + Number("20");
将输出 30
将此应用于您的代码:
price.push(Number(bookPrice));
【讨论】:
以上是关于从数组中添加值的问题的主要内容,如果未能解决你的问题,请参考以下文章