rol*_*ger 5 javascript type-conversion local-storage angularjs
我在应用程序的 localStorage 中存储了很多值,并且需要一种将“字符串”转换回数字的方法 - 如果它是数字。想法是,如果您<input type="number"> on your form, then the data going into the form and extracted from the form IS a number, but once stored - its converted to a string. So to repopulate that稍后强制使用 HTML 字段,则必须读取 localStorage 值并将其转换回数字,然后再重新填充输入字段 - 否则您会开始收到大量重复警告,有时还会收到错误,因为需要 NUMBERS,但 localStorage 正在检索字符串。
我的方法:假设输入的值是数字,那么只会存储一个数字(仅数字) - 因此您可以假设只会出现数字(即使它们是字符串)。只知道会返回数字可以实现这一点:
var allVariables = {} ;
var reg = new RegExp(/^\d+$/) ; // this accounts for digits only
for (var x=0; x<localStorage.length;x++) {
var keyValue = localStorage.getItem(localStorage.key(x)) ;
if (reg.text(keyValue)) {
keyValue = parseInt(keyValue) ;
}
allVariables[localStorage.key(x)] = keyValue ;
}
Run Code Online (Sandbox Code Playgroud)
我什至对此进行了扩展,以解释真/假布尔值...不能轻松使用 0/1 而不与数字混淆。我见过的另一种方法是在键名上加下划线来标识 typeof 以便以后转换:
IE:
key1_str
key2_boo
key3_int
key4_obj
key5_flo
Run Code Online (Sandbox Code Playgroud)
然后识别“_xxx”以适当地转换该值。
我要求看看其他人解决这个问题的方法或关于如何改进它的建议和建议。我的并不完美...虽然 localStorage 也不完美...但仍在寻求改进。
Bis*_*day 10
假设你有"keyName" : "12345"。棘手的解决方案是:
var newInt = +localStorage.getItem('keyName')
Run Code Online (Sandbox Code Playgroud)
这个额外的 + 会将字符串转换为整数。
您可以考虑将整个对象存储到较少数量的存储键中,而不是存储大量单个键,然后将其字符串化为 json 并在检索时进行解析。JSON 方法将保留类型
var obj= {
id:100,
anotherProp:'foo'
}
localStorage.setItem('myObj',JSON.stringify(obj));
var newObj = JSON.parse(localStorage.getItem('myObj'));
console.log(typeof newObj.id)//number
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7583 次 |
| 最近记录: |