1

I have a list of arrays received from PHP response.[1], response.[2], response.[3], ... etc. I want in jQuery Loop create these variables and alert them. but I get this error in Console "bill is not defined"

var i;
for (i = 1; i < 4; ++i) {
  var bill[i] = response[i].sum;
  alert(bill[i]);
}

5
  • 1
    Then do it, what is the problem ? Commented Oct 25, 2018 at 17:53
  • 1
    Define it outside of the loop var bill = []; Commented Oct 25, 2018 at 17:54
  • @ZakariaAcharki I tried that too 'var bill1 = response[1].sum;' Commented Oct 25, 2018 at 17:56
  • Ok, Then what is the problem? Commented Oct 25, 2018 at 17:57
  • @ZakariaAcharki I get these bill is not defined. it seems i value is not attached to variable Commented Oct 25, 2018 at 17:58

1 Answer 1

2

You could use window[] that will define the variable globally or you could use eval() like :

var response = [{
  sum: 0
}, {
  sum: 11
}, {
  sum: 22
}, {
  sum: 33
}];

for (var i = 1; i < 4; ++i) {
  window['bill_' + i] = response[i].sum;
  //console.log(window['bill_' + i]);
}

for (var i = 1; i < 4; ++i) {
  console.log(window['bill_' + i]);
}

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a specific reason to not implement it with the fix in your comment?
After reading the question another time I have noticed that the author says create these variables and alert them
Oh, I missed that part :)
can I make console.log(bill1); dynamic too ? Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.