JavaScript / JQuery를 사용하여 간단한지도를 만드는 방법
이 질문에는 이미 답변이 있습니다.
- JavaScript Hashmap 동등 답변 17 개
이 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);
}
편집 : 오래된 답변, ECMAScript 2015 (ES6) 표준 자바 스크립트에는 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);
일반 객체를 사용하십시오.
var map = { key1: "value1", key2: "value2" }
function get(k){
return map[k];
}
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;
};
}
이것은 오래된 질문이지만 기존 답변이 매우 위험 할 수 있으므로 여기에서 우연히 발견 될 미래의 사람들을 위해이 답변을 남기고 싶었습니다 ...
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:
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 one entry with the String key [object Object]
:
> JSON.stringify(map);
{"[object Object]": 2}
This is clearly not a 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/Map although a glance at the Browser Compatability table there will show that this isn't ready to used in general purpose web apps yet.
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
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.
var map = {'myKey1':myObj1, 'mykey2':myObj2};
// You don't need any get function, just use
map['mykey1']
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();
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
참고URL : https://stackoverflow.com/questions/4246980/how-to-create-a-simple-map-using-javascript-jquery
'Programing' 카테고리의 다른 글
비동기 함수를 호출하는 동안 mocha 테스트에서 시간 초과 오류를 피하는 방법 : 시간 초과 2000ms 초과 (0) | 2020.05.16 |
---|---|
MYSQL 업데이트 명령문 내부 조인 테이블 (0) | 2020.05.16 |
캔버스 요소에서 요소를 그린 후 불투명도 (알파, 투명도)를 변경하는 방법은 무엇입니까? (0) | 2020.05.16 |
안드로이드 APK의 패키지 이름을 읽으십시오 (0) | 2020.05.16 |
Android API 21 툴바 패딩 (0) | 2020.05.16 |