0

I have the following:

var offset;
offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level) || 0;
offset += 100;

When I use the debugger this offset now has 0100. I want it to add like a number not a string. How can I do this?

Please note I changed the question slightly because I realized I was getting the value from local storage. I assume this returns a string. But I am still not sure how to solve this.

4

1 回答 1

2

The code you gave won't do that. I assume your value in your actual code is a numeric string. If so, the + will behave as a string concatenation operator, so you must convert the value to a number before using +.

You can do that with parseFloat().

var offset = localStorage.getItem('test.MenuList.Offset.' + examID + "." + level);

offset = parseFloat(offset) || 0;

Or in most cases, you can simply use the unary version of + to do the conversion.

offset = +offset || 0;
于 2012-10-07T13:40:40.927 回答