2015-10-11 129 views
0

我想要你的帮助。我在做我的大学作业。我正在处理IndexedDB。我想做一些加法,减去来自我的indexedDB作为对象的数据。我正在从IndexedDB中检索值,并将其保存以供将来用于应用算术运算。IndexedDB中的算术运算

当我总结数据,然后它连接数字。

例如:

总+ =价格[指数]。名称; //在价格数组中有数据像100,50,20 我的输出应该是这些值的总和。但我得到这样的输出“1005020”

我不知道如何添加此数据。这是我的代码。

function GetData(){ 
 
\t var output = document.getElementById("printOutput"); 
 
\t \t \t \t \t var product=[]; 
 
\t \t \t \t \t var price=[]; 
 
\t \t \t \t \t var person=[]; 
 
\t \t \t \t \t var index=0; 
 
\t \t \t \t \t var total = 0; 
 
        var transaction = db.transaction("accounts", IDBTransaction.READ_WRITE); 
 
        var objectStore = transaction.objectStore("accounts"); 
 
    
 
        var request = objectStore.openCursor(); 
 
        request.onsuccess = function(evt) { 
 
        
 
\t \t \t \t \t var cursor = evt.target.result; 
 
         
 
          if(cursor) 
 
\t \t \t \t \t \t \t { 
 
\t \t \t \t \t \t \t \t product.push({name: cursor.value.pType}); 
 
\t \t \t \t \t \t \t \t price.push({name: cursor.value.pPrice}); 
 
\t \t \t \t \t \t \t \t person.push({name: cursor.value.personID}); 
 
\t \t \t \t \t \t \t \t cursor.continue(); 
 
\t \t \t \t \t \t \t } 
 
        while(product.length!=index) 
 
\t \t \t \t \t { 
 
\t \t \t \t \t \t if(person[index].name==1){ 
 
\t \t \t \t \t \t var element = document.createElement("p"); 
 
\t \t \t \t \t \t element.textContent = product[index].name+"\t"+price[index].name; 
 
\t \t \t \t \t \t output.appendChild(element); 
 
\t \t \t \t \t \t total = total + price[index].name; 
 
\t \t \t \t \t \t } 
 
\t \t \t \t \t \t index++; 
 
\t \t \t \t \t } 
 
\t \t \t \t \t var sum = document.createElement("p"); 
 
\t \t \t \t \t sum.textContent = "Total Amount = " + total; 
 
\t \t \t \t \t output.appendChild(sum); \t \t \t \t \t 
 
\t 
 
        };}

+0

通常数据从IDB在字符串对象的形式检索的,所以你的“+”操作符串联,而不是增加。因此,首先将您的字符串转换为数字,然后执行加法。转换 - https://www.google.co.in/search?q=javascript+convert+string+to+number&ie=utf-8&oe=utf-8&gws_rd=cr&ei=240aVqXGLpCWuATrl5SoCw。这将解决您的问题,但请让我知道如果它没有帮助。 – hagrawal

+0

感谢您的帮助。有效!! –

+0

还有一件事。有没有任何工具可以调试我的代码。我想调试我的代码,以便我可以验证哪一行代码完全不起作用。我正在使用NotePad ++ –

回答

1

对于人前往因此提出,通过注释解决,下面是溶液:

通常数据从IDB检索在字符串对象的形式,所以你 “+ “运算符连接而不是添加。因此,首先将 字符串转换为数字,然后执行加法。为了转化 请参阅here

+1

IDB可以存储任何可以通过https://html.spec.whatwg.org/multipage/infrastructure.html#safe-passing-of-structured-data进行克隆的值 - 最好是将数字数据存储为数字,而不是存储为字符串并在每次检索时进行转换。但是如果太晚了,数据已经存储为字符串,答案是正确的, –