开发者

JS: Can "false" be type-coerced to false?

When you use Html5 localStorage values are stored as strings. This is something you need to deal with if you want to store the state of a checkbox and then restore it at a later date. I was hoping that something like this would work:

(function() {
  function e(id) { return document.getElementById(id); }

  e('save').addEventListener('click', function() {
   localStorage['check-value'] = e('check开发者_运维技巧box').checked
  })
  e('checkbox').checked = localStorage['check-value'];
})();

But it seems that 'check-value' will store something along the lines of "false" if the box is not checked and the string "false" gets type-coerced to true on that second-to-last line. I know that I could make a little if-test but this is for a hobby project and I want to figure it out if possible. Can "false" be coerced to false?

I'm not using libraries for this btw because its a chrome extension and I want to keep it lightweight.


"false" is just a string like any other, you would need to do your own check here.


You can test whether it's equal to the string "false":

e('checkbox').checked = localStorage['check-value'] != 'false';

Alternatively, you can coerce it to a number before you store it and after you retrieve it:

localStorage['check-value'] = +e('checkbox').checked
// ...
e('checkbox').checked = +localStorage['check-value']


You can try using JSON.parse to pull out the value. Ideally you would also use JSON.stringify to serialize objects etc. You can make this more manageable by abstracting it away behind some other interface.

JSON.parse("false") == false

Example for a wrapper:

var LocalStorageManager = new (function () {
   this.set = function (key, object) {
      localStorage[key] = JSON.stringify(object);
   };

   this.get = function (key) {
      return JSON.parse(localStorage[key]);
   };
});


You can't really do that on JS. You should use var boolValue = (stringValue !== 'false') or whatever floats your boat.


Change this line:

e('checkbox').checked = localStorage['check-value'];

to this:

e('checkbox').checked = localStorage['check-value'] == "true";

or depending upon what you want:

e('checkbox').checked = localStorage['check-value'] != "false";

If you do this more than a couple times, wrap the boolean local storage access in a tiny little function that returns only boolean true or false.

function tfStr(val) {
    return(val === "true");
}


Just riffing here but you could do something really stupid like

eval(localStorage['check-value'])

If the string is false it will evaluate to the boolean false. Obviously you don't want to do that since it's a major security hole.

Alternatively you could use a ternary operator:

(localStorage['check-value']==="false")?false:localStorage['check-value'];

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜