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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3559070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:43:09  来源:igfitidea点击:

are there dictionaries in javascript like python?

javascriptpython

提问by l--''''''---------''''''''''''

i need to make a dictionary in javascript like this

我需要像这样用javascript制作字典

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?

javascript中有这样的东西吗?

采纳答案by Chief

This is an old post, but I thought I should provide an illustrated answer anyway.

这是一篇旧帖子,但我认为无论如何我都应该提供一个图解的答案。

Use javascript's object notation. Like so:

使用 javascript 的对象表示法。像这样:

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:

或者您可以使用 javascript 文字对象表示法,其中键不需要用引号引起来:

states_dictionary={ 
     CT:["alex","harry"], 
     AK:["liza","alex"], 
     TX:["fred", "harry"]
};

回答by Adam

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

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

回答by Alex

There are no real associative arrays in Javascript. You can try using objects:

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

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.

然而,对于对象,不可能使用典型的数组属性或方法,如 array.length。至少可以在 for-in 循环中访问“对象数组”。

回答by MickMalone1983

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:

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

http://jsfiddle.net/MickMalone1983/VEpFf/2/

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.

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

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

回答by mquandalle

Firefox 13+ provides an experimental implementation of the mapobject similar to the dictobject in python. Specifications here.

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

It's only avaible in firefox, but it looks better than using attributes of a new Object(). Citation from the documentation :

它仅在 Firefox 中可用,但它看起来比使用new Object(). 文档中的引用:

  • 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 Objectare Strings, where they can be any value for a Map.
  • You can get the size of a Mapeasily while you have to manually keep track of size for an Object.
  • 一个对象有一个原型,所以地图中有默认的键。但是,这可以使用 绕过map = Object.create(null)
  • an 的键ObjectStrings,它们可以是 a 的任何值Map
  • 您可以Map轻松获取 .a 的大小,而您必须手动跟踪Object.

回答by Vaibhav

Have created a simple dictionary in JS here:

在 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";
        }
    }
}

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.

这只是一个基本的模拟。它可以通过实现更好的运行时间算法来进一步优化,以至少在 O(nlogn) 或更低的时间复杂度下工作。像对数组进行合并/快速排序,然后进行一些 B-search 查找。我没有尝试或搜索有关在 JS 中映射哈希函数的信息。

Also, Key and Value for the JSdict obj can be turned into private variables to be sneaky.

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

Hope this helps!

希望这可以帮助!

EDIT >> After implementing the above, I personally used the JS objects as associative arrays that are available out-of-the-box.

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

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)anddelete dict[key]

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

Read this post as a good resource on this implementation/usage. Dynamically creating keys in JavaScript associative array

阅读这篇文章作为有关此实现/用法的良好资源。 在 JavaScript 关联数组中动态创建键

THanks!

谢谢!

回答by CJStuart

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 Mapobject has been introduced, which is a dictionary implementation:

我意识到这是一个老问题,但是当你搜索“javascript字典”时它会在谷歌中弹出,所以我想补充一下上面的答案,在ECMAScript 6中,Map已经引入了官方对象,即字典执行:

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:

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