JavaScript中是否有字典实现?

56

我该如何在 JavaScript 中实现具有索引器的数组?.Net 中是否有类似于字典的东西?

9个回答

92

严格来说不行,但你可以像使用字典一样使用普通的JavaScript对象:

var a = {"a":"wohoo", 2:"hello2", "d":"hello"};
alert(a["a"]);
alert(a[2]);
alert(a["d"]);

4
如何迭代(遍历)字典? - Hosi
10
@Hosi:for(var x in a) { console.log(x, a[x]); } - 当在Chrome的JavaScript控制台中运行时,不要期望结果与定义的键的顺序相同,因为它是一个对象。 - shahkalpesh
3
之所以说它是“对象”不重要,而是因为它是一个无序集合。 - brushleaf
4
通常情况下这是有效的,但如果你的键中恰好包含 "toString" 或 "constructor" 等名称,就会出现不良的 bug。因此,我们必须始终使用 hasOwnProperty 来检查其是否存在。 - Peter
5
多么美丽的语言。 - Den
显示剩余5条评论

10

jQuery 的作者 John Resig 最近发表了一篇文章,介绍了 JavaScript 中的词典查询。

他的解决方案是将词典值分配为对象的属性。以下是从上述文章中粘贴下来的代码:

// The dictionary lookup object
var dict = {};
// Do a jQuery Ajax request for the text dictionary
$.get( "dict/dict.txt", function( txt ) {
  // Get an array of all the words
  var words = txt.split( "\n" );

  // And add them as properties to the dictionary lookup
  // This will allow for fast lookups later
  for ( var i = 0; i < words.length; i++ ) {
    dict[ words[i] ] = true;
  }

  // The game would start after the dictionary was loaded
  // startGame();
});

// Takes in an array of letters and finds the longest
// possible word at the front of the letters
function findWord( letters ) {
  // Clone the array for manipulation
  var curLetters = letters.slice( 0 ), word = "";

  // Make sure the word is at least 3 letters long
  while ( curLetters.length > 2 ) {
    // Get a word out of the existing letters
    word = curLetters.join("");

    // And see if it's in the dictionary
    if ( dict[ word ] ) {
      // If it is, return that word
      return word;
    }

    // Otherwise remove another letter from the end
    curLetters.pop();
  }
}

7
在我的上一个项目中,我被要求创建一个浏览器客户端应用程序,读取数万行数据,然后对数据进行分组和聚合,以便在网格和图表中显示。目标技术是HTML5、CSS3和EMCS5(2013年6月的现代浏览器)。由于不需要考虑旧版浏览器的兼容性,外部库仅限于D3(没有JQuery)。
我需要构建一个数据模型。我之前在C#中构建过一个数据模型,并依赖自定义字典对象来快速访问数据、分组和聚合。我已经多年没有使用JavaScript了,所以我开始搜索字典。我发现JavaScript仍然没有真正的本地字典。我找到了一些示例实现,但没有真正满足我的期望。所以我自己构建了一个字典。
正如我所提到的,我多年没有使用JavaScript了。进步(或者可能只是网络信息的可用性)非常令人印象深刻。我之前的所有工作都是基于类的语言,因此原型语言需要一些时间来适应(而且我还有很长的路要走)。
像大多数项目一样,这个项目在开始之前就已经到期了,所以我在学习的过程中犯了许多初学者的错误,这是从基于类的语言转换到基于原型的语言时所期望的。创建的字典是可用的,但是一段时间后,我意识到可以通过使其不那么新手入门来进行一些改进。项目在我有时间重新设计字典之前就已经资金耗尽了。哦,我的职位也同时失去了资金(真是令人惊讶)。因此,我决定使用我学到的知识重新创建字典,并确定字典是否实际上比数组更具性能优势。
/*
* Dictionary Factory Object
* Holds common object functions. similar to V-Table
* this.New() used to create new dictionary objects
* Uses Object.defineProperties so won't work on older browsers.
* Browser Compatibility (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties)
*      Firefox (Gecko) 4.0 (2), Chrome 5, IE 9, Opera 11.60, Safari 5
*/
function Dict() {

    /*
    * Create a new Dictionary
    */
    this.New = function () {
        return new dict();
    };

    /*
    * Return argument f if it is a function otherwise return undefined
    */
    function ensureF(f) {
        if (isFunct(f)) {
            return f;
        }
    }

    function isFunct(f) {
        return (typeof f == "function");
    }

    /*
    * Add a "_" as first character just to be sure valid property name
    */
    function makeKey(k) {
        return "_" + k;
    };

    /*
    * Key Value Pair object - held in array
    */
    function newkvp(key, value) {
        return {
            key: key,
            value: value,
            toString: function () { return this.key; },
            valueOf: function () { return this.key; }
        };
    };

    /*
    * Return the current set of keys. 
    */
    function keys(a) {
        // remove the leading "-" character from the keys
        return a.map(function (e) { return e.key.substr(1); });
        // Alternative: Requires Opera 12 vs. 11.60
        // -- Must pass the internal object instead of the array
        // -- Still need to remove the leading "-" to return user key values
        //    Object.keys(o).map(function (e) { return e.key.substr(1); });
    };

    /*
    * Return the current set of values. 
    */
    function values(a) {
        return a.map(function(e) { return e.value; } );
    };

    /*
    * Return the current set of key value pairs. 
    */
    function kvPs(a) {
        // remove the leading "-" character from the keys
        return a.map(function (e) { return newkvp(e.key.substr(1), e.value); });
    }

    /*
    * Returns true if key exists in the dictionary.
    * k - Key to check (with the leading "_" character) 
    */
    function exists(k, o) {
        return o.hasOwnProperty(k);
    }

    /*
    * Array Map implementation
    */
    function map(a, f) {
        if (!isFunct(f)) { return; }
        return a.map(function (e, i) { return f(e.value, i); });
    }

    /*
    * Array Every implementation
    */
    function every(a, f) {
        if (!isFunct(f)) { return; }
        return a.every(function (e, i) { return f(e.value, i) });
    }

    /*
    * Returns subset of "values" where function "f" returns true for the "value"
    */
    function filter(a, f) {
        if (!isFunct(f)) {return; }
        var ret = a.filter(function (e, i) { return f(e.value, i); });
        // if anything returned by array.filter, then get the "values" from the key value pairs
        if (ret && ret.length > 0) {
            ret = values(ret);
        }
        return ret;
    }

    /*
    * Array Reverse implementation
    */
    function reverse(a, o) {
        a.reverse();
        reindex(a, o, 0);
    }

    /**
    * Randomize array element order in-place.
    * Using Fisher-Yates shuffle algorithm.
    * (Added just because:-)
    */
    function shuffle(a, o) {
        var j, t;
        for (var i = a.length - 1; i > 0; i--) {
            j = Math.floor(Math.random() * (i + 1));
            t = a[i];
            a[i] = a[j];
            a[j] = t;
        }
        reindex(a, o, 0);
        return a;
    }
    /*
    * Array Some implementation
    */
    function some(a, f) {
        if (!isFunct(f)) { return; }
        return a.some(function (e, i) { return f(e.value, i) });
    }

    /*
    * Sort the dictionary. Sorts the array and reindexes the object.
    * a - dictionary array
    * o - dictionary object
    * sf - dictionary default sort function (can be undefined)
    * f - sort method sort function argument (can be undefined)
    */
    function sort(a, o, sf, f) {
        var sf1 = f || sf; // sort function  method used if not undefined
        // if there is a customer sort function, use it
        if (isFunct(sf1)) {
            a.sort(function (e1, e2) { return sf1(e1.value, e2.value); });
        }
        else {
            // sort by key values
            a.sort();
        }
        // reindex - adds O(n) to perf
        reindex(a, o, 0);
        // return sorted values (not entire array)
        // adds O(n) to perf
        return values(a);
    };

    /*
    * forEach iteration of "values"
    *   uses "for" loop to allow exiting iteration when function returns true 
    */
    function forEach(a, f) {
        if (!isFunct(f)) { return; }
        // use for loop to allow exiting early and not iterating all items
        for(var i = 0; i < a.length; i++) {
            if (f(a[i].value, i)) { break; }
        }
    };

    /*
    * forEachR iteration of "values" in reverse order
    *   uses "for" loop to allow exiting iteration when function returns true 
    */
    function forEachR(a, f) {
        if (!isFunct(f)) { return; }
        // use for loop to allow exiting early and not iterating all items
        for (var i = a.length - 1; i > -1; i--) {
            if (f(a[i].value, i)) { break; }
        }
    }

    /*
    * Add a new Key Value Pair, or update the value of an existing key value pair
    */
    function add(key, value, a, o, resort, sf) {
        var k = makeKey(key);
        // Update value if key exists
        if (exists(k, o)) {
            a[o[k]].value = value;
        }
        else {
            // Add a new Key value Pair
            var kvp = newkvp(k, value);
            o[kvp.key] = a.length;
            a.push(kvp);
        }
        // resort if requested
        if (resort) { sort(a, o, sf); }
    };

    /*
    * Removes an existing key value pair and returns the "value" If the key does not exists, returns undefined
    */
    function remove(key, a, o) {
        var k = makeKey(key);
        // return undefined if the key does not exist
        if (!exists(k, o)) { return; }
        // get the array index
        var i = o[k];
        // get the key value pair
        var ret = a[i];
        // remove the array element
        a.splice(i, 1);
        // remove the object property
        delete o[k];
        // reindex the object properties from the remove element to end of the array
        reindex(a, o, i);
        // return the removed value
        return ret.value;
    };

    /*
    * Returns true if key exists in the dictionary.
    * k - Key to check (without the leading "_" character) 
    */
    function keyExists(k, o) {
        return exists(makeKey(k), o);
    };

    /*
    * Returns value assocated with "key". Returns undefined if key not found
    */
    function item(key, a, o) {
        var k = makeKey(key);
        if (exists(k, o)) {
            return a[o[k]].value;
        }
    }

    /*
    * changes index values held by object properties to match the array index location
    * Called after sorting or removing
    */
    function reindex(a, o, i){
        for (var j = i; j < a.length; j++) {
            o[a[j].key] = j;
        }
    }

    /*
    * The "real dictionary"
    */
    function dict() {
        var _a = [];
        var _o = {};
        var _sortF;

        Object.defineProperties(this, {
            "length": { get: function () { return _a.length; }, enumerable: true },
            "keys": { get: function() { return keys(_a); }, enumerable: true },
            "values": { get: function() { return values(_a); }, enumerable: true },
            "keyValuePairs": { get: function() { return kvPs(_a); }, enumerable: true},
            "sortFunction": { get: function() { return _sortF; }, set: function(funct) { _sortF = ensureF(funct); }, enumerable: true }
        });

        // Array Methods - Only modification to not pass the actual array to the callback function
        this.map = function(funct) { return map(_a, funct); };
        this.every = function(funct) { return every(_a, funct); };
        this.filter = function(funct) { return filter(_a, funct); };
        this.reverse = function() { reverse(_a, _o); };
        this.shuffle = function () { return shuffle(_a, _o); };
        this.some = function(funct) { return some(_a, funct); };
        this.sort = function(funct) { return sort(_a, _o, _sortF, funct); };

        // Array Methods - Modified aborts when funct returns true.
        this.forEach = function (funct) { forEach(_a, funct) };

        // forEach in reverse order
        this.forEachRev = function (funct) { forEachR(_a, funct) };

        // Dictionary Methods
        this.addOrUpdate = function(key, value, resort) { return add(key, value, _a, _o, resort, _sortF); };
        this.remove = function(key) { return remove(key, _a, _o); };
        this.exists = function(key) { return keyExists(key, _o); };
        this.item = function(key) { return item(key, _a, _o); };
        this.get = function (index) { if (index > -1 && index < _a.length) { return _a[index].value; } } ,
        this.clear = function() { _a = []; _o = {}; };

        return this;
    }


    return this;
}

在尝试理解类和原型对象之间的关系时,我有一个体悟,即原型实际上是用于创建对象的虚函数表(v-table)。此外,闭包中的函数也可以充当虚函数表的条目。随着项目的进展,我开始使用对象工厂(Object Factories),其中顶层对象包含对象类型的常见函数,并包括一个“this.New(args)”方法,用于创建解决方案中使用的实际对象。这是我为字典使用的样式。

字典的核心是一个数组(Array)、一个对象(Object)和一个键值对(KeyValuePair)对象。"addOrUpdate"方法接收一个键和一个值,并:

  1. 创建一个键值对(KeyValuePair)
  2. 使用键作为属性名,数组长度作为属性值,向对象添加一个新属性
  3. 将键值对(KeyValuePair)添加到数组中,使对象新属性的值成为数组中的索引。

注意:我了解到对象属性名称可以以“几乎任何”Unicode字符开头。该项目将涉及以“任何”Unicode字符开头的客户数据。为确保字典不会因为无效的属性名而崩溃,我在键前加了一个下划线(_),并在返回字典外部键时去掉该下划线。

为使字典正常工作,内部数组和对象必须保持同步。为确保此目的,数组和对象都不会在外部暴露。我想要避免意外更改,例如那些在"If"测试只有一个等号时会发生的更改,因为左侧值被误设的错误。

If(dict.KeyObj[“SomeKey”] = “oops”) { alert(“good luck tracing this down:-)”); }

这个典型的字典错误在出现计算、显示等 Bug(症状)时很难找到。因此,“this” 属性将无法访问其中任何一个。这种保护主义是我没有深入研究原型的原因之一。我曾想过使用内部对象与 Array 和 Object 一起暴露,并在使用“call”或“apply”方法时传递该内部对象,但我可能会稍后再看看,因为我仍然不确定我是否不必暴露那个内部对象,否则会使保护核心 Array 和 Object 的目的失效。
我纠正了我创建的第一个字典对象中的一些新手错误。
“Dict()”函数包含每个字典对象的大部分工作代码。决定使用封闭函数还是实际字典对象中的功能的标准如下:
- 大于一行的代码 - 由其他封闭函数使用 - 可能会发生更改导致增长,因为我发现了漏洞/问题
在可以理解的情况下使用了 Array 方法和属性名称。来自 C# 的我做了一些使我的字典可用性较差的事情,例如使用“Count”而不是“length”或“ForEach”而不是“forEach”。通过使用 Array 名称,字典现在在大多数情况下可以被用作 Array。不幸的是,我无法找到一种创建括号访问器的方法(例如,val = dict[key]),但这也可能是一件好事。当我考虑它时,我很难确定类似 val = dict[12] 的事情是否正确工作。数字 12 可以轻松地用作键,因此我想不出一个了解这种调用的“意图”的好方法。
完全封闭了下划线前缀处理。在我正在处理的项目中,我将其分散和重复放置在各种数据模型对象中。那看起来非常丑陋!

基准测试10K个带键的对象:加载/访问 - Firefox:25.5 / 20.4 Chrome:29.8 / 15.7 IE:25.7 / 18.8。请参见http://www.codeproject.com/Articles/684815/Would-JavaScript-Benefit-from-a-Dictionary-Object - Dan Ricker

5
在JS中,{"index":anyValue}就像一个字典。你也可以参考JSON的定义(http://www.json.org/)。

3
字典是一种将任意类型的值映射到另一个任意类型的值的容器。JavaScript中的“对象”强制使用字符串作为键,这太难以被称为字典了。 - pfalcon
此外,这与 JSON 没有任何关系。JSON 是一种文本格式信息,其中一些 JavaScript 数据结构可以被序列化。 - Heretic Monkey
感谢您的纠正@HereticMonkey。如果我年轻时的回答不准确,那么很抱歉。但从技术上讲,无论多么受限,JavaScript中的对象都可以被视为一种字典。请参考这两个维基页面https://en.wikipedia.org/wiki/Associative_array https://en.wikibooks.org/wiki/A-level_Computing/AQA/Paper_1/Fundamentals_of_data_structures/Dictionaries,其中维基百科还提到了JSON。 - Allen Hsu

3
ECMAScript 6(即2015年JavaScript规范)指定了一种名为Map的字典接口。它支持任意类型的任意键,具有只读size属性,不会像对象一样混杂着原型相关的东西,并且可以使用新的for...of...构造或Map.forEach进行迭代。请查看MDN 此处的文档和浏览器兼容性表此处

2

1

像其他人一样使用对象。如果您将除字符串以外的内容存储为键,则只需将它们转换为JSON格式。请参阅此博客文章,了解JavaScript中不同字典实现的性能考虑。


0

我已经实现了这个程序。第一次添加键值对使其成为了一种键类型安全的程序。

它运行良好,且不依赖于Map:

Git(始终更新)

function Dictionary() {

  this.dictionary = [];  
  this.validateKey = function(key){
    if(typeof key == 'undefined' || key == null){
        return false;
    }
    if(this.dictionary.length){
        if (!this.hasOwnProperty(this.dictionary[0], "key")) {
            return false;
        }
        if(typeof this.dictionary[0].key != typeof key){
            return false;
        }
    }
    return true;
  };
  this.hasOwnProperty = function (obj, prop) {
    var proto = obj.__proto__ || obj.constructor.prototype;
    return (prop in obj) &&
        (!(prop in proto) || proto[prop] !== obj[prop]);
    };
}



Dictionary.prototype = {

   Add: function(key, value) {
     if(!this.validateKey(key)){       
            return false;
     }
     if(!this.ContainsKey(key)){
      this.dictionary.push({ key: key, value: value });
      return true;
     }
     return false;
   },
   Any: function() {
     return this.dictionary.length > 0;
   },
   ContainsKey: function(key) {
     if(!this.validateKey(key)){       
            return false;
     }
      for (var i = 0; i < this.dictionary.length; i++) {
         var keyValuePair = this.dictionary[i];
         if (typeof keyValuePair != "undefined" && keyValuePair != null) {
            if (this.hasOwnProperty(keyValuePair, "key")) {
               if (keyValuePair.key == key) {
                  return true;
               }
            }
         }
      }
      return false;
   },
   ContainsValue: function(value) {
      for (var i = 0; i < this.dictionary.length; i++) {
         var keyValuePair = this.dictionary[i];
         if(typeof keyValuePair != "undefined" && keyValuePair != null){
                if (this.hasOwnProperty(keyValuePair, "value")) {
              if(value == null && keyValuePair.value == null){
                return true;
              }
              if ((value != null && keyValuePair.value == null) ||
                    (value == null && keyValuePair.value != null)) {
                  continue;
              }
              // compare objects content over json.
              if(JSON.stringify(value) === JSON.stringify(keyValuePair.value)){
                return true;
              }
            }
         }
      }
      return false;
   },
   Count: function() {
     return this.dictionary.length;
   },
   GetValue: function(key){
     if(!this.validateKey(key)){       
            return null;
     }
        for (var i = 0; i < this.dictionary.length; i++) {
         var keyValuePair = this.dictionary[i];
         if (typeof keyValuePair != "undefined" && keyValuePair != null) {
            if (this.hasOwnProperty(keyValuePair, "key")) {
               if (keyValuePair.key == key) {
                  return keyValuePair.value;
               }
            }
         }
      }
      return null;
   },
   Keys: function(){
    var keys = [];
    for (var i = 0; i < this.dictionary.length; i++) {
      var keyValuePair = this.dictionary[i];
      if (typeof keyValuePair != "undefined" && keyValuePair != null) {
        if (this.hasOwnProperty(keyValuePair, "key")) {
          keys.push(keyValuePair.key);
        }
      }
    }
     return keys;
   },
   Remove: function(key){
    if(!this.validateKey(key)){       
            return;
    }
    for (var i = 0; i < this.dictionary.length; i++) {
         var keyValuePair = this.dictionary[i];
         if (typeof keyValuePair != "undefined" && keyValuePair != null) {
            if (this.hasOwnProperty(keyValuePair, "key")) {
               if (keyValuePair.key == key) {
                  this.dictionary.splice(i, 1);
                  return;                  
               }
            }
         }
      }
   },
   Values: function(){
    var values = [];
    for (var i = 0; i < this.dictionary.length; i++) {
      var keyValuePair = this.dictionary[i];
      if (typeof keyValuePair != "undefined" && keyValuePair != null) {
        if (this.hasOwnProperty(keyValuePair, "value")) {
          values.push(keyValuePair.value);
        }
      }
    }
     return values;
   },
};

这是使用它的方法:

var dic = new Dictionary();

var success = dic.Add("test", 5);
success = dic.Add("test1", 4);
success = dic.Add("test2", 8);
success = dic.Add(3, 8);
var containsKey = dic.ContainsKey("test2");
containsKey = dic.ContainsKey(3);

var containsValue = dic.ContainsValue(8);

var value = dic.GetValue("test1");

var keys = dic.Keys();
var values = dic.Values();

dic.Remove("test1");

var keys = dic.Keys();
var values = dic.Values();

0
var nDictionary = Object.create(null);

function setDictionary(index, value) {
    nDictionary[index] = value;
}

function getDictionary(index) {
    return nDictionary[index];
}

setDictionary(81403, "test 1");
setDictionary(81404, "test 2");
setDictionary(81405, "test 3");
setDictionary(81406, "test 4");
setDictionary(81407, "test 5");

alert(getDictionary(81403));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接