Saya menulis peta di JS dengan fungsi traversal, tolong berkomentar.
//map.js
Array.prototype.remove = function (s) {for (var i = 0; i <this.length; i ++) {if (s == this [i]) this.splice (i, 1); }} /** * Peta sederhana * * * var m = peta baru (); * m.put ('key', 'value'); * ... * var s = ""; * M.each (fungsi (tombol, nilai, indeks) { * s+= index+":"+key+"="+value+"/n"; *}); * Peringatan; * * @author DeWitt * @Date 2008-05-24 */function Map () {/** Array untuk menyimpan tombol (digunakan untuk traversal) */this.keys = array baru (); / ** Simpan data*/ this.data = objek baru (); / ** * Masukkan key-value pair * @param {string} key * @param {objek} value */ this.put = function (key, value) {if (this.data [key] == null) {this.keys.push (key); } this.data [key] = value; }; / ** * Dapatkan nilai yang sesuai dengan tombol * @param {string} key * @return {objek} nilai */ this.get = function (key) {return this.data [key]; }; / *** Hapus pasangan nilai-kunci* @param {string} key*/ this.remove = function (key) {this.keys.remove (key); this.data [key] = null; }; / ** * Melintasi peta dan mengeksekusi fungsi pemrosesan * * @param {function} fungsi fungsi panggilan balik (key, value, index) {..} */ this.each = function (fn) {if (typeof fn! = 'Function') {return; } var len = this.keys.length; untuk (var i = 0; i <len; i ++) {var k = this.keys [i]; fn (k, this.data [k], i); }}; / *** Dapatkan array nilai-kunci (mirip dengan entriSSet java ())* @Return array objek nilai kunci {key, value}*/ this.entrys = function () {var len = this.keys.length; entri var = array baru (len); untuk (var i = 0; i <len; i ++) {entri [i] = {key: this.keys [i], value: this.data [i]}; } return entri; }; / *** Tentukan apakah peta kosong*/ this.isempty = function () {return this.keys.length == 0; }; / *** Dapatkan jumlah pasangan nilai kunci*/ this.size = function () {return this.keys.length; }; / ** * Tulis ulang ToString */ this.toString = function () {var s = "{"; untuk (var i = 0; i <this.keys.length; i ++, s+= ',') {var k = this.keys [i]; s+= k+"="+this.data [k]; } s+= "}"; kembali S; }; } function testMap () {var m = peta baru (); m.put ('key1', 'comtop'); m.put ('Key2', 'Southern Power Grid'); M.put ('Key3', 'Jingxin Garden'); peringatan ("init:"+m); m.put ('key1', 'Kantop'); alert ("Set Key1:"+M); M.Remove ("Key2"); peringatan ("Hapus Key2:"+m); var s = ""; m.each (fungsi (tombol, nilai, indeks) {s+= index+":"+key+"="+value+"/n";}); Peringatan; } //testmap.htm? <html> <head> <title> peta tes </iteme> <bahasa skrip = "javaScript" src = "map.js"> </script> </head> <body> <input type = "value =" test "onclick =" testmap () "> </body> ht" ht "htl" onclick = "testmap ()"> </body>Artikel di atas adalah contoh peta JavaScript sederhana (berbagi) yang merupakan semua konten yang saya bagikan dengan Anda. Saya harap Anda dapat memberi Anda referensi dan saya harap Anda dapat mendukung wulin.com lebih lanjut.