使用html5 localstorage可以找到某个键​​值对应的索引

发布于 2024-09-13 18:05:15 字数 229 浏览 5 评论 0原文

window.localStorage.setItem("Georgia","Atlanta") 
var x=window.localStorage.getItem("Georgia")

我在本地存储中存储了 50 个州和最大城市的列表。 使用上面的代码我可以轻松检索亚特兰大是“佐治亚州”最大的城市。 有没有一种简单的方法可以进行反向查找并搜索“Atlanta”并获得“Georgia”?

window.localStorage.setItem("Georgia","Atlanta") 
var x=window.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"?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紙鸢 2024-09-20 18:05:16

本地存储是从键到值的简单映射,所以不是。没有方法可以查找值的键,或者更准确地说,查找键,因为可能有多个。

您还可以存储城市->州的反向表来完成此操作:

// 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 之间是否存在/什么关系?”

理想情况下,您应该将它们放在两个不同的表中,以区分您正在谈论的关系类型(即州->城市和城市->州),但在这个简单的情况下应该没问题。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文