开发者

Using html5 localstorage can I find the index corresponding to a key value

开发者 https://www.devze.com 2023-01-11 07:04 出处:网络
window.localStorage.setItem(\"Georgia\",\"Atlanta\") var x=window开发者_Go百科.localStorage.getItem(\"Georgia\")
window.localStorage.setItem("Georgia","Atlanta") 
var x=window开发者_Go百科.localStorage.getItem("Georgia")

I have a list of 50 states and the largest city stored in localstorage. Using the code above I can easily retrieve that Atlanta is the largest city for "Georgia". Is there an easy way to do a reverse lookup and search for "Atlanta" and get "Georgia"?


Local Storage is a simple map from key to value, so no. There is no method to look up the key for a value, or more accurately, the keys because there may be more than one.

You could additionally store a reverse table of city->state to accomplish this:

// 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

So now setItem() means "there is a relationship between X and Y" and getItem() means "is there a / what is the relationship between X and Y?"

Ideally you'd have these in two different tables to separate out what type of relationship you're talking about (i.e., state->city and city->state) but you should be okay in this simple case.

0

精彩评论

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