Javascript JQuery 是否支持 Dictionaries (key, value) 集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5402180/
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-08-23 17:02:18  来源:igfitidea点击:

Does JQuery support Dictionaries (key, value) collection?

javascriptjquerycollectionsdictionary

提问by Homam

Does JQuery support Dictionaries(key, value) collection ?

JQuery 是否支持Dictionaries(key, value) 集合?

I would like to set the following data in a structure

我想在结构中设置以下数据

[1, false]
[2, true]
[3, false]

with the ability to add, lookup, delete and update.

具有添加、查找、删除和更新的能力。

Any help!

任何帮助!

回答by Guffa

No, jQuery doesn't, but Javascript does.

不,jQuery 没有,但 Javascript 有。

Just use an object:

只需使用一个对象:

var dict = {
  "1" : false,
  "2" : true,
  "3" : false
};

// lookup:
var second = dict["2"];
// update:
dict["2"] = false;
// add:
dict["4"] = true;
// delete:
delete dict["2"];

回答by Felix Kling

jQuery, no. But JavaScript does. There are only two structures in JavaScript, arraysand objects.

jQuery,没有。但是 JavaScript 可以。JavaScript 中只有两种结构,数组对象

Objects can be used as dictionary, where the properties are the "keys":

对象可以用作字典,其中属性是“键”:

var dict = {
    1: true,
    2: true,
    3: false
};

Properties of objects can be either accessed with dot notation, obj.property(if the property name is a valid identifier, which a digit as used above is not) or with array access notation, obj['property'].

对象的属性可以使用点符号访问obj.property(如果属性名称是有效标识符,上面使用的数字不是)或使用数组访问符号obj['property'].

回答by Geo

You don't need separate dictionary classes, since Javascript objects act as dictionaries. See this:

您不需要单独的字典类,因为 Javascript 对象充当字典。看到这个:

var userObject = {}; // equivalent to new Object()
userObject["lastLoginTime"] = new Date();
alert(userObject["lastLoginTime"]);

Full article here: http://msdn.microsoft.com/en-us/magazine/cc163419.aspx

全文在这里:http: //msdn.microsoft.com/en-us/magazine/cc163419.aspx

回答by Mithun Sreedharan

With pure JavaScript,

使用纯 JavaScript,

var myDictionary = new Object();
myDictionary[1] = false;
myDictionary[2] = true;
myDictionary[3] = false;

function look(i) { return myDictionary[i];}
look(1); // will return false

回答by Beno?t

Yes, you can use object to do this:

是的,您可以使用 object 来执行此操作:

var myDict = { 1:false , 2:true , 3:false };