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

l--*_*''' 82 javascript python

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

我不记得确切的符号,但它是这样的:

states_dictionary={ CT=[alex,harry], AK=[liza,alex], TX=[fred, harry] ........ }
Run Code Online (Sandbox Code Playgroud)

在javascript中有这样的东西吗?

Chi*_*ief 105

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

使用JavaScript的对象表示法.像这样:

states_dictionary={ 
     "CT":["alex","harry"], 
     "AK":["liza","alex"], 
     "TX":["fred", "harry"]
};
Run Code Online (Sandbox Code Playgroud)

并访问值:

states_dictionary.AK[0] //which is liza
Run Code Online (Sandbox Code Playgroud)

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

states_dictionary={ 
     CT:["alex","harry"], 
     AK:["liza","alex"], 
     TX:["fred", "harry"]
};
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,第一个例子应该使用完全相同的语法在两种语言中产生相同的对象,除了结束';'.states_dictionary = {"CT":["alex","harry"],"AK":["liza","alex"],"TX":["fred","harry"]} (10认同)
  • 实际上,Python 允许语句终止分号,因此第一个示例在 Python 和 JavaScript 中都完全有效 (3认同)
  • @JohnDemetriou的主要区别是javascript对象表示法键必须是字符串(用双引号""括起来).对象表示法在JSON中可以看到数据交换,并受到文字对象表示法的启发; 值得注意的是,JSON通常用于字符串上下文中 (2认同)

Ale*_*lex 46

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

var x = new Object();
x["Key"] = "Value";
Run Code Online (Sandbox Code Playgroud)

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

  • 由于o ["key"]相当于Javascript中的o.key,性能几乎相同.但是性能取决于Javascript引擎/ Web浏览器.这些之间存在很多差异,特别是在旧版本中. (5认同)
  • 性能如何?在对象恒定时间内查找关键字? (3认同)

Vai*_*hav 10

在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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在可以使用上面的实现来模拟字典:

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!"
Run Code Online (Sandbox Code Playgroud)

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

此外,JSdict obj的Key和Value可以变成隐私的私有变量.

希望这可以帮助!

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

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

即:dict.hasOwnProperty(键) 删除词典[键]

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

谢谢!


CJS*_*art 10

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

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");
Run Code Online (Sandbox Code Playgroud)

与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({});
Run Code Online (Sandbox Code Playgroud)


Ada*_*dam 5

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