如何使用 JavaScript/JQuery 创建一个简单的地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4246980/
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-23 11:34:12  来源:igfitidea点击:

How to create a simple map using JavaScript/JQuery

javascriptjqueryhashmap

提问by Marcus Leon

How can you create the JavaScript/JQuery equivalent of this Java code:

您如何创建与此 Java 代码等效的 JavaScript/JQuery:

Map map = new HashMap(); //Doesn't not have to be a hash map, any key/value map is fine
map.put(myKey1, myObj1);
map.put(myKey2, myObj2); //Repeat n times

function Object get(k) {
    return map.get(k);
}

回答by Simen Echholt

Edit: Out of date answer, ECMAScript 2015 (ES6) standard javascript has a Map implementation, read here for more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

编辑:过时的答案,ECMAScript 2015 (ES6) 标准 javascript 有一个 Map 实现,阅读这里了解更多信息:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

var map = new Object(); // or var map = {};
map[myKey1] = myObj1;
map[myKey2] = myObj2;

function get(k) {
    return map[k];
}

//map[myKey1] == get(myKey1);

回答by Simon

Just use plain objects:

只需使用普通对象:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}

回答by Jade

function Map() {
    this.keys = new Array();
    this.data = new Object();

    this.put = function (key, value) {
        if (this.data[key] == null) {
            this.keys.push(key);
        }
        this.data[key] = value;
    };

    this.get = function (key) {
        return this.data[key];
    };

    this.remove = function (key) {
        this.keys.remove(key);
        this.data[key] = null;
    };

    this.each = function (fn) {
        if (typeof fn != 'function') {
            return;
        }
        var len = this.keys.length;
        for (var i = 0; i < len; i++) {
            var k = this.keys[i];
            fn(k, this.data[k], i);
        }
    };

    this.entrys = function () {
        var len = this.keys.length;
        var entrys = new Array(len);
        for (var i = 0; i < len; i++) {
            entrys[i] = {
                key: this.keys[i],
                value: this.data[i]
            };
        }
        return entrys;
    };

    this.isEmpty = function () {
        return this.keys.length == 0;
    };

    this.size = function () {
        return this.keys.length;
    };
}

回答by Rich

This is an old question, but because the existing answers could be very dangerous, I wanted to leave this answer for future folks who might stumble in here...

这是一个老问题,但因为现有的答案可能非常危险,我想把这个答案留给未来可能会在这里绊倒的人......

The answers based on using an Object as a HashMap are broken and can cause extremely nasty consequences if you use anything other than a String as the key. The problem is that Object properties are coerced to Strings using the .toString method. This can lead to the following nastiness:

基于将对象用作 HashMap 的答案已被破坏,如果您使用 String 以外的任何其他内容作为键,可能会导致极其恶劣的后果。问题是使用 .toString 方法将对象属性强制转换为字符串。这可能会导致以下问题:

function MyObject(name) {
  this.name = name;
};
var key1 = new MyObject("one");
var key2 = new MyObject("two");

var map = {};
map[key1] = 1;
map[key2] = 2;

If you were expecting that Object would behave in the same way as a Java Map here, you would be rather miffed to discover that map only contains oneentry with the String key [object Object]:

如果您期望 Object 的行为方式与此处的 Java Map 相同,那么您会很恼火地发现该映射仅包含一个带有 String 键的条目[object Object]

> JSON.stringify(map);
{"[object Object]": 2}

This is clearly nota replacement for Java's HashMap. Bizarrely, given it's age, Javascript does not currently have a general purpose map object. There is hope on the horizon, though: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Mapalthough a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.

这显然不是针对Java的HashMap中的替代品。奇怪的是,鉴于它的年龄,Javascript 目前没有通用的地图对象。不过,希望在地平线上:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map虽然浏览器兼容性表会显示这不是准备在通用网络应用程序中使用。

In the meantime, the best you can do is:

与此同时,你能做的最好的事情是:

  • Deliberately use Strings as keys. I.e. use explicit strings as keys rather than relying on the implicit .toString-ing of the keys you use.
  • Ensure that the objects you are using as keys have a well-defined .toString() method that suits your understanding of uniqueness for these objects.
  • If you cannot/don't want to change the .toString of the key Objects, when storing and retrieving the entries, convert the objects to a string which represents your understanding of uniqueness. E.g. map[toUniqueString(key1)] = 1
  • 故意使用字符串作为键。即使用显式字符串作为键,而不是依赖于您使用的键的隐式 .toString-ing。
  • 确保您用作键的对象具有定义良好的 .toString() 方法,该方法适合您对这些对象唯一性的理解。
  • 如果您不能/不想更改关键对象的 .toString,则在存储和检索条目时,将对象转换为代表您对唯一性的理解的字符串。例如map[toUniqueString(key1)] = 1

Sometimes, though, that is not possible. If you want to map data based on, for example File objects, there is no reliable way to do this because the attributes that the File object exposes are not enough to ensure its uniqueness. (You may have two File objects that represent different files on disk, but there is no way to distinguish between them in JS in the browser). In these cases, unfortunately, all that you can do is refactor your code to eliminate the need for storing these in a may; perhaps, by using an array instead and referencing them exclusively by index.

但有时,这是不可能的。如果要基于 File 对象等映射数据,则没有可靠的方法来执行此操作,因为 File 对象公开的属性不足以确保其唯一性。(你可能有两个 File 对象代表磁盘上的不同文件,但在浏览器中的 JS 中没有办法区分它们)。不幸的是,在这些情况下,您所能做的就是重构您的代码以消除将这些存储在一个可能的需要;也许,通过使用数组并通过索引专门引用它们。

回答by David

var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']

回答by polydor

If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();

如果您不限于使用 JQuery,则可以使用prototype.js 框架。它有一个叫做 Hash 的类:你甚至可以一起使用 JQuery 和 prototype.js。只需输入 jQuery.noConflict();

var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values