问题:像python这样的javascript中有字典吗?
我需要像这样用javascript制作字典
我不记得确切的符号了,但是有点像:
states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }
javascript中有这样的事情吗?
i need to make a dictionary in javascript like this
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?
回答 0
这是一篇旧文章,但我认为无论如何我都应该提供一个图解的答案。
使用javascript的对象符号。像这样:
states_dictionary={
"CT":["alex","harry"],
"AK":["liza","alex"],
"TX":["fred", "harry"]
};
并访问值:
states_dictionary.AK[0] //which is liza
或者您可以使用javascript文字对象表示法,其中键不需要用引号引起来:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
This is an old post, but I thought I should provide an illustrated answer anyway.
Use javascript’s object notation. 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:
states_dictionary={
CT:["alex","harry"],
AK:["liza","alex"],
TX:["fred", "harry"]
};
回答 1
直到2015年(ECMAScript 6发行版),Javascript中都没有真正的关联数组。从那时起,您可以将Map对象用作Robocat状态。在MDN中查找详细信息。例:
let map = new Map();
map.set('key', {'value1', 'value2'});
let values = map.get('key');
如果不支持ES6,则可以尝试使用对象:
var x = new Object();
x["Key"] = "Value";
但是,对于对象,无法使用典型的数组属性或方法,例如array.length。至少可以在for-in-loop中访问“对象数组”。
There were no real associative arrays in Javascript until 2015 (release of ECMAScript 6). Since then you can use the Map object as Robocat states. Look up the details in 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:
var x = new Object();
x["Key"] = "Value";
However with objects it is not possible to use typical array properties or methods like array.length. At least it is possible to access the “object-array” in a for-in-loop.
回答 2
我意识到这是一个古老的问题,但是当您搜索“ javascript词典”时,它会在Google中弹出,因此我想在上述答案中加上ECMAScript 6中Map
引入的官方对象,它是字典实施:
var dict = new Map();
dict.set("foo", "bar");
//returns "bar"
dict.get("foo");
与javascript的普通对象不同,它允许任何对象作为键:
var foo = {};
var bar = {};
var 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({});
I realize this is an old question, but it pops up in Google when you search for ‘javascript dictionaries’, so I’d like to add to the above answers that in ECMAScript 6, the official Map
object has been introduced, which is a dictionary implementation:
var dict = new Map();
dict.set("foo", "bar");
//returns "bar"
dict.get("foo");
Unlike javascript’s normal objects, it allows any object as a key:
var foo = {};
var bar = {};
var 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({});
回答 3
在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!"
这只是一个基本的模拟。可以通过实施更好的运行时间算法以使其至少达到O(nlogn)时间复杂度甚至更低的复杂度来对其进行进一步优化。像对数组进行合并/快速排序,然后对查询进行一些B搜索。我没有尝试或搜索过有关在JS中映射哈希函数的信息。
另外,可以将JSdict obj的键和值转换为私有变量,以防止偷偷摸摸。
希望这可以帮助!
编辑>>完成上述操作后,我个人使用了JS对象作为现成可用的关联数组。
但是,我想特别提到两种方法,它们实际上被证明有助于使它成为方便的哈希表体验。
即:dict.hasOwnProperty(key) 并 删除dict [key]
阅读这篇文章,作为有关此实现/用法的好资源。
在JavaScript关联数组中动态创建键
谢谢!
Have created a simple dictionary in JS here:
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";
}
}
}
The above implementation can now be used to simulate a dictionary as:
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. Like merge/quick sort on arrays and then some B-search for lookups.
I Didn’t give a try or searched about mapping a hash function in JS.
Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.
Hope this helps!
EDIT >>
After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.
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]
Read this post as a good resource on this implementation/usage.
Dynamically creating keys in JavaScript associative array
THanks!
回答 4
使用JavaScript对象。您可以访问它们的属性,例如字典中的键。这是JSON的基础。语法类似于Python字典。请参阅:JSON.org
Use JavaScript objects. You can access their properties like keys in a dictionary. This is the foundation of JSON. The syntax is similar to Python dictionaries. See: JSON.org
回答 5
一个老问题,但是最近我需要做一个AS3> JS端口,为了提高速度,我为JS写了一个简单的AS3样式的Dictionary对象:
http://jsfiddle.net/MickMalone1983/VEpFf/2/
如果您不知道,AS3词典允许您使用任何对象作为键,而不仅仅是字符串。一旦您发现它们的用途,它们就会非常方便。
它的速度不如本地对象快,但是在这方面,我还没有发现任何重大问题。
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
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:
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. 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
回答 6
Firefox 13+提供了map
类似于dict
python中对象的实验性实现。规格在这里。
它仅在firefox中可用,但看起来比使用a的属性更好new Object()
。来自文档的引用:
- 对象具有原型,因此地图中包含默认键。但是,可以使用绕过此操作
map = Object.create(null)
。
- 的键
Object
是Strings
,其中它们可以是的任何值Map
。
Map
当您必须手动跟踪的大小时,您可以轻松获得大小Object
。
Firefox 13+ provides an experimental implementation of the map
object similar to the dict
object in python. Specifications here.
It’s only avaible in firefox, but it looks better than using attributes of a 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)
.
- The keys of an
Object
are Strings
, where they can be any value for a Map
.
- You can get the size of a
Map
easily while you have to manually keep track of size for an Object
.