我需要在JavaScript中创建这样一个字典:
我不记得确切的符号,但它大概是这样的:
我不记得确切的符号,但它大概是这样的:
states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }
在JavaScript中有这样的东西吗?
states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }
在JavaScript中有这样的东西吗?
这是一篇旧帖,但我仍然想提供一个图解答案。
使用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"]
};
Object.hasOwnProperty.call(dictionary, key)
(否则用户可以输入valueOf的值,而dictionary ['valueOf']
返回属于对象原型的Object.valueOf()
函数,这可能不是您的代码所期望的 - 可能会出现错误或安全问题)。 如果键不是字符串类型,则需要小心,否则隐式数字和toString转换将导致问题。 ES6 Map
类型已被设计为为字典提供扩展功能。 - robocat在2015年之前(即ECMAScript 6的发布之前),Javascript中没有真正的关联数组。自从那时起,您可以像Robocat所说的那样使用Map对象。在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循环中访问“对象数组”。
Map
对象,它是一个字典实现:let dict = new Map();
dict.set("foo", "bar");
//returns "bar"
dict.get("foo");
与 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({});
没有办法使用用户定义的键比较器,因此,如果您不想进行身份验证比较,那么您仍然只能像使用普通对象一样使用数字或字符串键。
dict = {key: value}
? - Joe Sadoskifunction 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!"
一个古老的问题,但最近我需要进行AS3>JS端口,并为了速度,我编写了一个简单的AS3风格的JS字典对象:
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
map
对象的实现,类似于Python中的dict
对象。只能在Firefox中使用,但它比使用new Object()
的属性看起来更好。文档中引用的话说:
Object
有一个原型,因此地图中有默认键。但是,可以使用map = Object.create(null)
绕过这一点。Object
的键是字符串,而Map
的键可以是任何值。Map
的大小,而必须手动跟踪Object
的大小。