简体   繁体   English

检查 localStorage 中的值是否大于先前的值

[英]check if value in localStrorage is greater than previous value

I am setting an item in localStorage我在 localStorage 中设置一个项目

{typeof window.== 'undefined' && localStorage,setItem('userData'. topic.progress)}

and then I want to check to see if the value is greater than or less than the previous value, only values greater than should then be set.然后我想检查该值是否大于或小于前一个值,只有大于的值才应该设置。

However currently it is always changing to the progress value even if the value is lower但是目前它总是改变为进度值,即使该值较低

my data looks like this:我的数据如下所示:

{
topic1: { progress: '20'},
topic2: {progress: '25'},
topic3: {progress: '30'}
}


let progress = ''

  if (localStorage.getItem('userData') !== null && localStorage.getItem('userData') > progress) {
    progress = localStorage.getItem('userData')
  } else if (localStorage.getItem('userData') < progress) {
    console.log('less than')
  }

The value returned by localStorage.getItem() is always a string. localStorage.getItem()返回的值始终是一个字符串。
You need to convert the value to a number , eg:您需要将值转换为数字,例如:

const numericLS = parseInt( localStorage.getItem('userData'), 10 );

Changing the data type to string everywhere does not help, because string comparison compares character-by-character, not by the numeric value, eg:将数据类型更改为字符串无济于事,因为字符串比较是逐个字符而不是数值比较,例如:

"9" < "89" // false
"9" < "90" // true

Example:例子:

localStorage.setItem('userData', 25);

var progressValues = [ 2, 3, 20, 25, 200, 30 ]; // <--- use numeric values

progressValues.forEach( function( progress ){
  const LS = localStorage.getItem('userData');

  const numericLS = parseInt( LS, 10 );  // <--- convert to number

  if( numericLS < progress ){
    console.log('set larger', progress, ', was', numericLS);
    localStorage.setItem('userData', progress);
  } else {
    console.log('skip smaller', progress, ', keep', numericLS);
  }
})

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

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