javascript 我可以用 Map<String, Object> 之类的东西在 jquery 中存储数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3267868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:41:32  来源:igfitidea点击:

Something like a Map<String, Object> I can use to store data in jquery?

javascriptjquery

提问by user246114

I have some JSON objects I'd like to store in a map for the lifetime of my app. For example, my app shows a listing of Farms. When a user clicks one of the Farm links, I download a Farm representation as JSON:

我有一些 JSON 对象,我想在我的应用程序的整个生命周期中将它们存储在地图中。例如,我的应用程序显示了一个农场列表。当用户单击 Farm 链接之一时,我将 Farm 表示下载为 JSON:

Farm 1
Farm 2
...
Farm N

every time the user clicks one of those links, I download the entire Farm object. Instead, I'd like to somehow make a global map of Farms, keyed by their ID. Then when the user clicks one of the above links, I can see if it's already in my map cache and just skip going to the server.

每次用户单击这些链接之一时,我都会下载整个 Farm 对象。相反,我想以某种方式制作一个农场的全球地图,以他们的 ID 为键。然后当用户单击上述链接之一时,我可以查看它是否已经在我的地图缓存中,然后跳过去服务器。

Is there some general map type like this that I could use in jquery?

是否有一些像这样的通用地图类型可以在 jquery 中使用?

Thanks

谢谢

回答by Felix Kling

What about a JavaScript object?

JavaScript 对象呢?

var map = {};

map["ID1"] = Farm1;
map["ID2"] = Farm2;
...

Basically you only have two data structure in JavaScript: Arrays and objects.

JavaScript 中基本上只有两种数据结构:数组和对象。

And fortunately objects are so powerful, that you can use them as maps / dictionaries / hash table / associative arrays / however you want to call it.

幸运的是,对象是如此强大,您可以将它们用作地图/字典/哈希表/关联数组/无论您想怎么称呼它。

You can easily test if an ID is already contained by:

您可以轻松测试 ID 是否已包含在:

if(map["ID3"]) // which will return undefined and hence evaluate to false

回答by spender

The object type is the closest you'll get to a map/dictionary.

对象类型是最接近地图/字典的类型。

var map={};
map.farm1id=new Farm(); //etc

回答by R. Hill

farmMap = {};
farmMap['Farm1'] = Farm1;
...