-1

What's wrong with this code? Can anyone help out?

var read=new Array("i=10","j=20","k=i*j");
for(var i=0;i<read.length;i++)
{
    alert(eval(read[i]));
}

Expecting output:

alert three times with values 10,20,200.

But actual output:

But alert Once with value 10.
iCollect.it Ltd
  • 92,391
  • 25
  • 181
  • 202

3 Answers3

3

When the loop executes the first time, you are setting i = 10, with eval. So the loop breaks out immediately.

So, you might want to change the loop variable to something else, like this

var read = new Array("i=10","j=20","k=i*j");
for(var idx=0; idx < read.length; idx++)
{
    console.log(eval(read[idx]));
}

Output

10
20
200

Note: Please make sure that you read this question and the answers to that question, before using eval in your code.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

Try this code

var read=new Array("i=10","j=20","k=i*j");
for(var index=0;index<read.length;index++)
{
alert(eval(read[index]));
}
-1

while the loop is executing, at the first execution of i=10 the i variable is set to 10; so loop will be terminated because of the condition i<read.length (here... 10<3) remains false.

see the eval() tutorial.

Bhavesh G
  • 3,000
  • 4
  • 39
  • 66