5

I've been searching for an answer but I'm only getting results regarding the Google maps API. I'm trying to use a map in JavaScript to map an integer to a string. Everything is working fine in Firefox but in chrome I get an error message in the console:

Uncaught ReferenceError: Map is not defined

Below is a piece of reference code:

var NameMap;
var DistanceMap;

function FillMaps(){
    NameMap = new Map();
    DistanceMap = new Map();

    NameMap.set(01, "Araba/Álava");
}

function CheckName(_field){
    var value = document.getElementsByName(_field.name).item(0).value;
    var location = value.charAt(0) + value.charAt(1);
    var result = NameMap.get(parseInt(location));
    if(result == undefined){
        result = "Unknown";
    }
    document.getElementById('loc').innerHTML = result;
}
Rob W
  • 341,306
  • 83
  • 791
  • 678
Nick
  • 461
  • 2
  • 6
  • 16

4 Answers4

7

Some ES harmony features, including Map(), did already exist in Chrome at the end of 2011. It's just disabled by default.

To enable the feature, visit chrome://flags/, and enable "Enable experimental JavaScript". Then restart the browser and enjoy the new features.

An alternative method is to pass the --js-flags=--harmony flag on the command line. For instance:

chromium --js-flags=--harmony
chrome.exe --jsflags=--harmony
Rob W
  • 341,306
  • 83
  • 791
  • 678
1

Map is now in Chrome version 38 (beta as of 29-Aug-2014), which means it will get to stable very shortly. If you have 38, no need to enable experimental features.

Marc Rochkind
  • 3,678
  • 3
  • 30
  • 38
0

Why not use a simple array?

var NameMap;
var DistanceMap;

function FillMaps(){
    NameMap = new Array();
    DistanceMap = new Array();

    NameMap[01]="Araba/Álava";

}

function CheckName(_field){
    var value = document.getElementsByName(_field.name).item(0).value;
    var location = value.charAt(0) + value.charAt(1);
    var result = NameMap[parseInt(location)];
    if(result == undefined){
        result = "Unknown";
    }
    document.getElementById('loc').innerHTML = result;
}
user2313067
  • 593
  • 1
  • 3
  • 8
  • True, I could use an array for my example doh! But I might need to map a string to a string in the future, any ideas to fix it in chrome? – Nick Jun 22 '13 at 13:48
  • An Object can be used for that. An array could do it too, but this is bad practice (see http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/). Map doesn't appear in the [javascript reference](http://www.w3schools.com/jsref/), I think it's added by firefox, though it doesn't even appear in the mozilla reference. – user2313067 Jun 22 '13 at 15:25
0

"Danger! Experimental technology!"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Its possible the code here can implement Map for Chrome, but I've not tried:

http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets

Spacedman
  • 92,590
  • 12
  • 140
  • 224