我想隱藏我的div如果沒有localStorage鍵值。如果localStorage鍵值不存在
隨着下面的行我只實現隱藏div時localStorage密鑰完全刪除,但需要做同樣的,如果localStorage 密鑰沒有得到任何價值只是[]。
window.localStorage.getItem('items') === null
它將如何執行?
我想隱藏我的div如果沒有localStorage鍵值。如果localStorage鍵值不存在
隨着下面的行我只實現隱藏div時localStorage密鑰完全刪除,但需要做同樣的,如果localStorage 密鑰沒有得到任何價值只是[]。
window.localStorage.getItem('items') === null
它將如何執行?
可以使用OR
運營商||
var items = window.localStorage.getItem('items')
if (items === null || items.length === 0)
{
// items is null, [] or '' (empty string)
}
添加必需的條件。如果你要檢查undefined
地方,以及你可以改變=== null
到== null
或像這樣
if (items === undefined || items === null || items.length === 0)
{
// items is undefined, null, [] or '' (empty string)
}
額外條件擴大
編輯:這裏是你可以做直接得到陣列
var items = JSON.parse(window.localStorage.getItem('items'))
if (items === null || items.length === 0)
{
// items is null or []
}
如何簡單:
if (!localStorage.nameOfYourLocalStorage) {
// do the following if the localStorage.nameOfYourLocalStorage does not exist
}
的怎麼可能是有用的一個例子:
if (!localStorage.nameOfYourLocalStorage) {
localStorage.nameOfYourLocalStorage = defaultValue;
}
這裏的腳本將檢查localStorage的名稱不存在,如果它不會,它會用默認值創建它。
如果你想它時,它確實存在行爲,你可以以後添加其他如果塊繼續,或刪除了「!'從'如果塊條件。
Storage.prototype.has = function(key) {
return (key in this && !(key in Storage.prototype));
};
你能提供更多信息嗎? – Phiter
謝謝Ma3x,但它在[]中的值字段中不起作用,也許它接受[]作爲字符? – qqruza
是的我想我已經修復它與 如果(項=== undefined || items === null || items.length <3) – qqruza
@qqruza:如果你有數組編碼爲JSON字符串,那麼你可以比較像這樣'items =='[]''或者先用'var itemsArray = JSON.parse(items)'解析,然後使用'itemsArray.length === 0'。 – Ma3x