dimanche 29 mars 2015

Get an object´s property by its name using a string

I have read quite often how to call a function using a string in JavaScript. But how can I get the property of an object on the same way? This post demonstrates how to use strings in order to call functions. How can I realize the same thing with object properties?


I tried this: Fiddle


But this line does not give me the desired result.



alert( window[val] );


What am I doing wrong ?


That´s the full code:



f1("obj.key");

function f1(val){
var obj={
key : "Hello World"
};
alert( obj.key ); // Hello World
alert( window[val] ); // undefined
}

Aucun commentaire:

Enregistrer un commentaire