Per operatore punto si può accedere ai valori da chiavi che non contengono caratteri dello spazio o speciali, parole che iniziano dal numero (cioè, quelli che non possono essere utilizzati come ad es. Nomi variabili) altrimenti è possibile ottenere qualsiasi riferimento a loro piace come chiavi nell'array associativo.
È possibile utilizzare come chiave tutto ciò che si desidera ma ricordare che la chiave sarà una rappresentazione in formato stringa di ciò che viene inserito. Chiarificazione: verrà chiamato toString().
sguardo:
var myObj = {};
myObj[ 3 ] = "key is 3";
alert(myObj[ "3" ]); //alerts "key is 3" because (3).toString() is "3"
//but an error will thrown when accessing by myObj.3
myObj[ {} ] = "key is {}"
alert(myObj["[object Object]"]) // alerts "key is {}" because ({}).toString() is "[object Object]"
È possibile ignorare toString()
metodo, ad esempio:
Object.prototype.toString = function(){ return "object"}
a = {};
a[ {} ] = "whatever";
alert(a["object"]); // alerts "whatever" because as now toString() returns "object" from each created object
Se non era permesso, si otterrebbe un errore. –