javascript - add a value to localstorage, instead of replacing it - Stack Overflow

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code, it replaces the entire value.

Code

$('#signUpButton').click(function() {
  var newUsername = $('#usernameSignInBox').val();
  signedUpUsernames.push(newUsername);
  localStorage.setItem('setUsernamesArray', signedUpUsernames);
});

i want the value from newUsername to be added to the localStorage setUsernamesArray, whereas in my code, it replaces the entire value.

Code

$('#signUpButton').click(function() {
  var newUsername = $('#usernameSignInBox').val();
  signedUpUsernames.push(newUsername);
  localStorage.setItem('setUsernamesArray', signedUpUsernames);
});
Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked Mar 5, 2016 at 11:47 igetstuckalotigetstuckalot 2373 gold badges8 silver badges16 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

If you want to add to the array, you must realise that the value in localStorage isn't an array, it is a string. If you want that string to represent an array, and you want to update that array, you must do the following things:

  • read the string, localStorage.getItem('setUsernamesArray'),
  • then convert it to an array with JSON.parse,
  • then push to the array,
  • and then store it again with localStorage.setItem('setUsernamesArray', JSON.stringify(array))

localStorage always store values as a string, so stringify your array and store,

localStorage.setItem('setUsernamesArray', JSON.stringify(signedUpUsernames));

And before reading it just parse it,

var arrayFrmStorage = JSON.parse(localStorage.getItem("setUsernamesArray"))

localStorage.setItem will replace value of the key in localStorage.

Consider localStorage as a variable. when you do

var a = "Hello";
a = " World"

value of a is replaced. To avoid it, we use +=

var a = "Hello";
a += " World"

Similarly, you will have to create another object with updated value and write this to localStorage.

Following is an example.

function setValueToLS(key, prop, value){
  var _local = {};
  if(localStorage.getItem(key))
    _local = JSON.parse(localStorage.getItem(key));

  _local[prop] = value;

  localStorage.setItem(key, JSON.stringify(_local));
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744377651a4571263.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信