简体   繁体   English

如何计算LocalStorage中存储的数字总和?

[英]How do I calculate the sum of numbers stored in LocalStorage?

I am new to JSON, so bear with me! 我是JSON新手,请多多包涵!

I am working on a website that stores values to LocalStorage via inputs. 我在一个通过输入将值存储到LocalStorage的网站上工作。 Each form input has the following function (only difference is formInput2, formInput3) 每个表单输入具有以下功能(唯一的区别是formInput2,formInput3)

function formInput(e) {
  // Save userInput from input
  // Get form values 
  var input = document.querySelector('.input').value;
  this.style.visibility = 'hidden';
  smtBtn.style.display = 'inline-block'
  var userInput = {
    answer: input
  }

  // Test if bookmark is null
  if (localStorage.getItem('bookmarks') === null) {
    // Init Array
    var bookmarks = [];
    // Add to array
    bookmarks.push(userInput);
    // Set to LocalStorage
    localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
  } else {
    // Get Bookmarks from LocalStorage 
    var bookmarks = JSON.parse(localStorage.getItem('bookmarks'));
    // Add bookmark to array 
    bookmarks.push(userInput);
    // Reset back to LocalStorage
    localStorage.setItem('bookmarks', JSON.stringify(bookmarks));
  }

  // Refetch bookmarks
  fetchBookmarks();

  // Prevent form from submitting
  e.preventDefault();
}

I need to add the three numbers that are in local storage, and I am using this function: 我需要添加本地存储中的三个数字,并且正在使用此功能:

function bookmarkMath() {
   var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
    total = 0,
    i;
  for (i = 0; i < bm1.length; i++) {
    total += bm1[i].answers;
  }
  console.log(total);
}
}

But alas, my output is NaN. 但是,我的输出是NaN。 :( :(

Any help would be very appreciated!!!!!!! 任何帮助将不胜感激!!!!!!!

edit: In dev tools, this is what I get back with console.log(LocalStorage) - the numbers I have entered in the form on the site. 编辑:在开发工具中,这就是我用console.log(LocalStorage)返回的内容-我在网站上的表单中输入的数字。

    Storage {bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]", length: 1}
    bookmarks: "[{"answer":"2"},{"answer":"4"},{"answer":"5"}]"
    length: 1
    __proto__: Storage

Edit 2: I have updated the second ]function to include the JSON.parse. 编辑2:我已经更新了第二个[]函数,以包含JSON.parse。 But now I am getting just the numbers 0245 as my result, NOT the sum of 0+2+4+5. 但是现在我得到的只是数字0245,而不是0 + 2 + 4 + 5的总和。 Any help?? 有帮助吗? :p :p

You are on the right track by doing JSON.parse() . 通过执行JSON.parse()您将走上正确的道路。 However, the value is in a string. 但是,该值在字符串中。 You can see quote at the value it is mean will be threated as a string. 您可以看到引号的值表示该值将威胁为字符串。 You should convert it to number format like following: 您应该将其转换为数字格式,如下所示:

total += parseInt(bm1[i].answers);


If you don't want to do parseInt() then your output should be : 如果您不想执行parseInt()则输出应为:

{"answer": 2} //this one mean your value is Number 

Instead: 代替:

{"answer":"2"} //this one mean your value is in String

I think I see it ... this statement looks "wrong, yet something that JavaScript would accept!" 我想我明白了……这句话看起来“错了,但是JavaScript会接受的!”

  var bm1 = JSON.parse(localStorage.getItem('bookmarks')),
    total = 0,
    i;

Notice the commas. 注意逗号。

Instead, write this as three separate lines: 而是将其写为三行:

var var bm1 = JSON.parse(localStorage.getItem('bookmarks'));
var total = 0;
var i;
const bookmarks = JSON.parse(localStorage.getItem('bookmarks')) || []
const totalAnswers = bookmarks.map(o => +o.answer).reduce((a, b) => a + b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM