繁体   English   中英

javascript中是否有像python这样的字典?

[英]are there dictionaries in javascript like python?

我需要像这样用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"]
};

直到 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 中访问“对象数组”。

在 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({});

无法使用用户定义的键比较器,因此如果您不希望进行身份比较,您仍然只能像使用普通对象一样使用数字或字符串键。

在这里用 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-search 查找。 我没有尝试或搜索在 JS 中映射哈希函数。

此外,可以将 JSdict obj 的 Key 和 Value 转换为私有变量以便偷偷摸摸。

希望这可以帮助!

编辑 >> 实现上述内容后,我个人将 JS 对象用作开箱即用的关联数组。

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

即: dict.hasOwnProperty(key)删除 dict[key]

阅读这篇文章作为关于这个实现/使用的一个很好的资源。 在 JavaScript 关联数组中动态创建键

谢谢!

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

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

Firefox 13+ 提供了map对象的实验性实现,类似于 python 中的dict对象。 规格在这里

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

  • 一个对象有一个原型,所以地图中有默认键。 但是,这可以使用map = Object.create(null)绕过。
  • Object的键是Strings ,它们可以是Map的任何值。
  • 您可以轻松获得Map的大小,而您必须手动跟踪Object的大小。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM