循环时从localStorage求和值

时间:2013-04-30 19:18:37

标签: javascript jquery function

我一遍又一遍地找到了关于如何对值进行求和的相同例子,但我无法自己使用它。我在localStorage中保存了两组数据。两个键的第一个值是我想要一起添加的数字。我发现许多.each函数执行循环但我想在查看键/值对时执行此操作,让变量包含和作为键/值对循环。所以这就是我所拥有的:

$(document).ready(function(){
if(localStorage.length > 0){
    for (var i=0, len=localStorage.length; i<len; i++){
        var sum = 0;
        var key = localStorage.key(i); 
        var val = localStorage.getItem(key);
        var valu = val.split("*");
        alert (valu[0]); //alerts twice 130 and 160
        sum += valu[0]; //didn't do anything
        sum += parseInt(valu[0]); //also didn't work
        alert (sum);
    }
}
});

因此,这两个值分别为130和160,它们会在函数循环时发出警告...所以如何添加它们并在循环时具有运行总计?

1 个答案:

答案 0 :(得分:1)

你需要循环外的var sum = 0;,如下所示:

$(document).ready(function(){
    if(localStorage.length > 0){
        var sum = 0;
        for (var i=0, len=localStorage.length; i<len; i++){
            var key = localStorage.key(i); 
            var val = localStorage.getItem(key);
            var valu = val.split("*");
            alert (valu[0]); //alerts twice 130 and 160
            sum += parseInt(valu[0]); //also didn't work
            alert (sum);
        }
    }
});