有像python这样的javascript中的字典吗?

时间:2010-08-24 17:15:19

标签: javascript python

我需要在这样的javascript中制作字典

我不记得确切的符号,但它类似于:

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

javascript中有这样的东西吗?

7 个答案:

答案 0 :(得分:101)

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

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

答案 1 :(得分:45)

Javascript中没有真正的关联数组。您可以尝试使用对象:

var x = new Object();
x["Key"] = "Value";

但是对于对象,不可能使用典型的数组属性或array.length等方法。至少可以在for-in-loop中访问“object-array”。

答案 2 :(得分:9)

在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的Key和Value可以变成隐私的私有变量。

希望这有帮助!

编辑&gt;&gt; 在实现上述之后,我个人使用JS对象作为开箱即用的关联数组。

然而,我想特别提一下实际证明有助于使其成为方便的哈希表体验的两种方法。

Viz: dict.hasOwnProperty(key) 删除字典[key]

阅读这篇文章作为此实施/用法的良好资源。 Dynamically creating keys in JavaScript associative array

谢谢!

答案 3 :(得分:9)

我意识到这是一个老问题,但是当你搜索“javascript词典”时它会弹出谷歌,所以我想在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({});

答案 4 :(得分:4)

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

答案 5 :(得分:3)

一个老问题,但我最近需要做一个AS3&gt; 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

答案 6 :(得分:1)

Firefox 13+提供了map对象的实验性实现,类似于python中的dict对象。 Specifications here

它只能在firefox中使用,但它看起来比使用new Object()的属性更好。来自文档的引文:

  
      
  • 对象有一个原型,因此地图中有默认键。但是,可以使用map = Object.create(null)
  • 绕过此功能   
  • Object的密钥为Strings,其中Map可以是Map的任何值。
  •   
  • 当您必须手动跟踪Object的尺寸时,您可以轻松获得{{1}}的尺寸。
  •