Javascript 中有 Python 这样的字典吗?

我需要用 javascript 做一个这样的字典

我不记得确切的记号了,但是大概是这样的:

states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }

Javascript 里有这种东西吗?

194389 次浏览

使用 JavaScript 对象。您可以像字典中的键一样访问它们的属性。这是 JSON 的基础。语法类似于 Python 字典。见: JSON.org

在2015年之前,Javascript 中没有真正的关联数组(ECMAScript 6的发布)。从那时起,您可以使用 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 中访问“ object-array”。

这是一篇老文章,但我认为无论如何我应该提供一个说明性的答案。

使用 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"]
};

一个老问题,但是我最近需要做一个 AS3 > JS 端口,为了速度起见,我为 JS 编写了一个简单的 AS3风格的 Dictionary 对象:

Http://jsfiddle.net/mickmalone1983/vepff/2/

如果您不知道,AS3字典允许您使用任何对象作为键,而不仅仅是字符串。一旦你发现它们的用途,它们就会派上用场。

它不像本地对象那样快,但是我没有发现它在这方面有任何明显的问题。

空气污染指数:

//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

Firefox13 + 提供了类似于 python.说明书在这里中的 dict对象的 map对象的实验性实现。

它只能在 firefox 中使用,但是它看起来比使用 new Object()的属性要好:

  • 一个对象有一个原型,因此在映射中有默认的键。但是,这可以使用 map = Object.create(null)绕过。
  • Object的键是 Strings,它们可以是 Map的任意值。
  • 你可以很容易地得到一个 Map的大小,而你必须手动跟踪一个 Object的大小。

在 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 (非登录)时间复杂度甚至更低的情况下。比如对数组进行合并/快速排序,然后进行 B 搜索查找。 我没有尝试或搜索在 JS 中映射散列函数。

此外,JSdictobj 的 Key 和 Value 可以转换为私有变量,以保持隐蔽性。

希望这个能帮上忙!

编辑 > > 在实现以上内容之后,我个人使用 JS 对象作为可以开箱即用的关联数组。

但是 ,我想特别提一下两个方法,它们实际上证明对于创建方便的哈希表体验是有帮助的。

即: HasOwnProperty (key) 还有 删除命令[键]

阅读这篇文章,作为这个实现/用法的一个很好的参考资料。 在 JavaScript 关联数组中动态创建键

谢谢!

在 ECMAScript 6中,引入了官方的 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({});

不可能有用户定义的键比较器,所以如果您不希望进行身份比较,那么仍然只能使用数字或字符串键,就像使用普通对象那样。