简体   繁体   English

如何计算 localStorage 中的字符串数而不是其中的字符数

[英]How to count the number of Strings in localStorage and not the number of characters in it

Can anyone tell me how to count the number of Strings present in localStorage and not the number of characters in it.谁能告诉我如何计算 localStorage 中存在的字符串数,而不是其中的字符数。 I wrote localStorage.getItem('id').length to see how many numbers of Strings are being saved, but it doesn't count the number of Strings present in "id" .我写了 localStorage.getItem('id').length 来查看保存了多少个字符串,但它不计算"id"中存在的字符串数。 It just counts the number of characters present in it.它只计算其中存在的字符数。 For example, this ( ["A","Roshan"] ) are the Strings which are being saved in localStorage and when I use .length method, it should show the result as 2 and not 14. Whatever it may be, here are the codes where you can see how I save it in localStorage例如,这个 ( ["A","Roshan"] ) 是保存在 localStorage 中的字符串,当我使用.length方法时,它应该将结果显示为 2 而不是 14。不管它是什么,这里是您可以在其中看到我如何将其保存在 localStorage 中的代码

var newName=document.getElementById('name').value;

if (localStorage.getItem('id') == null) 
{ 
     localStorage.setItem('id', '[]'); 
} 

var old_names = JSON.parse(localStorage.getItem('id')); 

 old_names.push(newName); 
    
 localStorage.setItem('id', JSON.stringify(old_names)); 
const ids = ['1','2','3'] // user ids

//set the ids inside local storage

localStorage.setItem('id', JSON.stringify(ids))

//get the ids back from local storage

if('id' in localStorage){
  const ids = JSON.parse(localStorage.getItem('id'))
  console.log(`total ids in local storage ${ids.length}`)
}

sample code示例代码

<p id="counter"> names counter : <span>0</span></p>

<p>
  name : <input type="text" id="name" value="">
  <button id="bt-add-name">add</button>
</p>
const
  names_Storage = JSON.parse(localStorage.getItem('names') || '[]')
, e_counter     = document.querySelector('#counter span')
, e_name        = document.querySelector('#name')
  ;

e_counter.textContent = names_Storage.length

document.querySelector('#bt-add-name').onclick = e =>
  {
  let newName = e_name.value.trim()

  if (newName)
    {
    names_Storage.push( newName )
    e_counter.textContent = names_Storage.length
    localStorage.setItem('names', JSON.stringify(names_Storage))
    e_name.value = ''
    e_name.focus()
    }
  }

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

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