Friday, September 21, 2007

Concatenating Object with String using eval()

eval() is a neat function that evaluates a string and executes it as if it was script
code.

Consider this code:

function displayItem(itemNo){
var item1 = "111";
var item2 = "222";
var item3 = "333";

eval("alert(item"+itemNo+")"); // the 'item' variable is concatenated with the parameter passed
}

and when call with this statement:

displayItem(1);

it will alert:

111

or in other case:

displayItem(3);

it will alert:

333

No comments: