2010-08-09 89 views
0
window.localStorage.setItem("Georgia","Atlanta") 
var x=window.localStorage.getItem("Georgia") 

我有一個列表,包含50個州和存儲在localstorage中的最大城市。 使用上面的代碼,我可以輕鬆地檢索出亞特蘭大是「格魯吉亞」最大的城市。 有沒有簡單的方法來做反向查找和搜索「亞特蘭大」並獲得「格魯吉亞」?使用html5 localstorage可以找到與鍵值對應的索引

回答

1

本地存儲是一個從關鍵到價值的簡單映射,所以沒有。沒有辦法查找某個值的關鍵字,或者更準確地說,關鍵字s,因爲可能有多個關鍵字。

你可以另外存儲都市的反轉表>狀態來實現:

// Georgia's largest city is Atlanta 
window.localStorage.setItem("Georgia", "Atlanta") 

// What is Georgia's largest city? 
var x=window.localStorage.getItem("Georgia") // returns Atlanta 

// Atlanta is in Georgia 
window.localStorage.setItem("Atlanta", "Georgia") 

// What state does Atlanta belong to? 
var y=window.localStorage.getItem("Atlanta") // returns Georgia 

所以現在setItem()的意思是「有X和Y之間的關係」,並getItem()手段「是有/什麼是X和Y之間的關係?「

理想情況下,您應該在兩張不同的表格中分別列出您所談論的關係類型(即州 - >城市和城市 - >州),但在這種簡單情況下應該沒問題。