[英]are there dictionaries in javascript like python?
i need to make a dictionary in javascript like this我需要像这样用javascript制作字典
i dont remember the exact notation, but it was something like:我不记得确切的符号,但它是这样的:
states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }
is there such a thing in javascript? javascript中有这样的东西吗?
This is an old post, but I thought I should provide an illustrated answer anyway.这是一篇旧帖子,但我认为无论如何我都应该提供一个说明性的答案。
Use javascript's object notation.使用 javascript 的对象表示法。 Like so:
像这样:
states_dictionary={
"CT":["alex","harry"],
"AK":["liza","alex"],
"TX":["fred", "harry"]
};
And to access the values:并访问这些值:
states_dictionary.AK[0] //which is liza
or you can use javascript literal object notation, whereby the keys not require to be in quotes:或者您可以使用 javascript 文字对象表示法,其中键不需要在引号中:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6).直到 2015 年(ECMAScript 6 发布),Javascript 中才出现真正的关联数组。 Since then you can use the Map object as Robocat states.
从那时起,您可以将 Map 对象用作 Robocat 状态。 Look up the details in MDN .
在 MDN 中查找详细信息。 Example:
例子:
let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');
Without support for ES6 you can try using objects:如果不支持 ES6,您可以尝试使用对象:
var x = new Object();
x["Key"] = "Value";
However with objects it is not possible to use typical array properties or methods like array.length.然而,对于对象,不可能使用典型的数组属性或像 array.length 这样的方法。 At least it is possible to access the "object-array" in a for-in-loop.
至少可以在 for-in-loop 中访问“对象数组”。
In ECMAScript 6, the official Map
object has been introduced, which is a dictionary implementation:在 ECMAScript 6 中,官方引入了
Map
对象,它是一个字典实现:
let dict = new Map();
dict.set("foo", "bar");
//returns "bar"
dict.get("foo");
Unlike javascript's normal objects, it allows any object as a key using identity comparison:与 javascript 的普通对象不同,它允许任何对象作为使用身份比较的键:
let foo = {};
let bar = {};
let dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");
//returns "Bar"
dict.get(bar);
//returns "Foo"
dict.get(foo);
//returns undefined, as {} !== foo and {} !== bar
dict.get({});
There is no way to have a user defined key comparator, so if you do not desire identity comparison, you are still stuck with only using number or string keys like with a normal object.无法使用用户定义的键比较器,因此如果您不希望进行身份比较,您仍然只能像使用普通对象一样使用数字或字符串键。
Have created a simple dictionary in JS here:在这里用 JS 创建了一个简单的字典:
function JSdict() {
this.Keys = [];
this.Values = [];
}
// Check if dictionary extensions aren't implemented yet.
// Returns value of a key
if (!JSdict.prototype.getVal) {
JSdict.prototype.getVal = function (key) {
if (key == null) {
return "Key cannot be null";
}
for (var i = 0; i < this.Keys.length; i++) {
if (this.Keys[i] == key) {
return this.Values[i];
}
}
return "Key not found!";
}
}
// Check if dictionary extensions aren't implemented yet.
// Updates value of a key
if (!JSdict.prototype.update) {
JSdict.prototype.update = function (key, val) {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
// Verify dict integrity before each operation
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Values[i] = val;
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Adds a unique key value pair
if (!JSdict.prototype.add) {
JSdict.prototype.add = function (key, val) {
// Allow only strings or numbers as keys
if (typeof (key) == "number" || typeof (key) == "string") {
if (key == null || val == null) {
return "Key or Value cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
return "Duplicate keys not allowed!";
}
}
this.Keys.push(key);
this.Values.push(val);
}
else {
return "Only number or string can be key!";
}
}
}
// Check if dictionary extensions aren't implemented yet.
// Removes a key value pair
if (!JSdict.prototype.remove) {
JSdict.prototype.remove = function (key) {
if (key == null) {
return "Key cannot be null";
}
if (keysLength != valsLength) {
return "Dictionary inconsistent. Keys length don't match values!";
}
var keysLength = this.Keys.length;
var valsLength = this.Values.length;
var flag = false;
for (var i = 0; i < keysLength; i++) {
if (this.Keys[i] == key) {
this.Keys.shift(key);
this.Values.shift(this.Values[i]);
flag = true;
break;
}
}
if (!flag) {
return "Key does not exist";
}
}
}
var dict = new JSdict();
dict.add(1, "one")
dict.add(1, "one more")
"Duplicate keys not allowed!"
dict.getVal(1)
"one"
dict.update(1, "onne")
dict.getVal(1)
"onne"
dict.remove(1)
dict.getVal(1)
"Key not found!"
This is just a basic simulation.这只是一个基本的模拟。 It can be further optimized by implementing a better running time algorithm to work in atleast O(nlogn) time complexity or even less.
它可以通过实现更好的运行时间算法来进一步优化,以至少 O(nlogn) 时间复杂度甚至更低。 Like merge/quick sort on arrays and then some B-search for lookups.
就像对数组进行合并/快速排序,然后进行一些 B-search 查找。 I Didn't give a try or searched about mapping a hash function in JS.
我没有尝试或搜索在 JS 中映射哈希函数。
Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.此外,可以将 JSdict obj 的 Key 和 Value 转换为私有变量以便偷偷摸摸。
Hope this helps!希望这可以帮助!
EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.编辑 >> 实现上述内容后,我个人将 JS 对象用作开箱即用的关联数组。
However , I would like to make a special mention about two methods that actually proved helpful to make it a convenient hashtable experience.但是,我想特别提一下实际上证明有助于使其成为方便的哈希表体验的两种方法。
Viz: dict.hasOwnProperty(key) and delete dict[key]即: dict.hasOwnProperty(key)并删除 dict[key]
Read this post as a good resource on this implementation/usage.阅读这篇文章作为关于这个实现/使用的一个很好的资源。 Dynamically creating keys in JavaScript associative array
在 JavaScript 关联数组中动态创建键
THanks!谢谢!
An old question but I recently needed to do an AS3>JS port, and for the sake of speed I wrote a simple AS3-style Dictionary object for JS:一个老问题,但我最近需要做一个 AS3>JS 端口,为了速度,我为 JS 编写了一个简单的 AS3 样式 Dictionary 对象:
http://jsfiddle.net/MickMalone1983/VEpFf/2/ http://jsfiddle.net/MickMalone1983/VEpFf/2/
If you didn't know, the AS3 dictionary allows you to use any object as the key, as opposed to just strings.如果您不知道,AS3 字典允许您使用任何对象作为键,而不仅仅是字符串。 They come in very handy once you've found a use for them.
一旦你找到它们的用途,它们就会非常方便。
It's not as fast as a native object would be, but I've not found any significant problems with it in that respect.它没有原生对象那么快,但在这方面我没有发现任何重大问题。
API:接口:
//Constructor
var dict = new Dict(overwrite:Boolean);
//If overwrite, allows over-writing of duplicate keys,
//otherwise, will not add duplicate keys to dictionary.
dict.put(key, value);//Add a pair
dict.get(key);//Get value from key
dict.remove(key);//Remove pair by key
dict.clearAll(value);//Remove all pairs with this value
dict.iterate(function(key, value){//Send all pairs as arguments to this function:
console.log(key+' is key for '+value);
});
dict.get(key);//Get value from key
Firefox 13+ provides an experimental implementation of the map
object similar to the dict
object in python. Firefox 13+ 提供了
map
对象的实验性实现,类似于 python 中的dict
对象。 Specifications here . 规格在这里。
It's only avaible in firefox, but it looks better than using attributes of a new Object()
.它仅在 Firefox 中可用,但它看起来比使用
new Object()
的属性更好。 Citation from the documentation :来自文档的引用:
- An Object has a prototype, so there are default keys in the map.
一个对象有一个原型,所以地图中有默认键。 However, this can be bypassed using
map = Object.create(null)
.但是,这可以使用
map = Object.create(null)
绕过。- The keys of an
Object
areStrings
, where they can be any value for aMap
.Object
的键是Strings
,它们可以是Map
的任何值。- You can get the size of a
Map
easily while you have to manually keep track of size for anObject
.您可以轻松获得
Map
的大小,而您必须手动跟踪Object
的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.