HTML and CSS Reference
In-Depth Information
because it means if you try to store an object, it actually stores
“[Object object]”. More importantly, this means numbers being
stored are actually being converted to strings, which can cause
errors in development.
To h i g h l i g h t t h e p To s s i b l e p r To b l e m s , h e r e 's a n e x a m p l e : L e t 's s a y
that Bruce runs a website selling videos of himself parading as a
professor of science. You've added a few of these videos to your
shopping basket because you're keen to learn more about “syn-
ergies.” The total cost of your shopping basket is $12, and this
cost is stored in sessionStorage. When you come to the checkout
page, Bruce has to add $5 in shipping costs. At an earlier point
during your application, $12 was stored in sessionStorage . This is
what your (contrived) code would look like:
sessionStorage.setItem('cost', 12);
// once shipping is added, Bruce's site tells you the total
¬ cost:
function costWithShipping(shipping) {
alert(sessionStorage.getItem('cost') + shipping);
}
// then it shows you the cost of the basket plus shipping:
costWithShipping(5);
If sessionStorage had stored the value as a number, you would
see an alert box showing 17. Instead, the cost of $12 was saved
as a string. Because JavaScript uses the same method for con-
catenation as it does for addition (for example, the plus symbol),
JavaScript sees this as appending a number to a string—so the
alert box actually shows 125—much more than you'd probably
be willing to pay to watch any video of Bruce! What's going on
here is type coercion, whereby upon storing the data in the stor-
age API, the data type is coerced into a string.
With this in mind, the API is (currently) actually:
readonly attribute unsigned long length;
getter DOMString key(in unsigned long index);
getter DOMString getItem(in DOMString key);
setter creator void setItem(in DOMString key, in DOMString
¬ data);
deleter void removeItem(in DOMString key);
void clear();
NOTE Where the specifi -
cation said we could store
“any data,” we can actually store
only DOMString data.
Search WWH ::




Custom Search