简体   繁体   中英

How to push dynamic values into an array in jquery

This is my array ARRAY

 ARRAY = ["A","B","C","D","E"];
 var mlength = ARRAY.length;

and my variables are

 var mname0 = a, var mname1 = b, var mname2 = c, var mname3 = d, var mname4 = e

 var month = JAN;

I am trying to push values to array based on mlength . I tries the below code but that's not working

  for (var i = 0, i < mlength; i++) {
      MARKETS[i].push(parseFloat(findDataForMonth(mname+i, month)) || null);
  }

That's not working. I am getting an error

How do I push the variables in for loop?

mname+i will not do what you think it's doing. Say that i is 2 . You might expect mname+i to return c (the value of variable mname2 ). Instead, what it will actually do is add mname (an undefined variable) + 2 , giving a ReferenceError .

Your mname0 , mname1 , etc. variables should be an array:

var mname = [a, b, c, d, e];

And then reference it like this:

findDataForMonth(mname[i], month)

Since the values in ARRAY and values of mname vars are the same (just the case is different), you could do the following.

var ARRAY = ["A","B","C","D","E"];
var mlength = ARRAY.length;
var month = JAN;
var mnames = ["a", "b", "c", "d", "e"];
//OR
//var mnames = [1, 2, 3, 4, 5];

for (var i = 0; i < mlength; i++) {
    var mname = mnames[i];
    //instead of mname+i just use mname
}

Your way:

1) Wrap the below code either in head or body with no ready handlers (such as window.onload dom ready etc.) as mname vars will be local and not avilable in the window scope otherwise.

var ARRAY = ["A","B","C","D","E"];
var mlength = ARRAY.length;
var mname0 = 'a';
var mname1 = 'b';
var mname2 = 'c';
var mname3 = 'd';
var mname4 = 'e';

for (var i = 0; i < mlength; i++) {
    alert (window['mname'+i]);
}

2) If you are to use the code in one of the ready handlers, you have 2 options. Either define your mname variable with no var keyword or prepend window. like below.

var ARRAY = ["A","B","C","D","E"];
var mlength = ARRAY.length;
mname0 = 'a'; // or window.mname0 = 'a';
mname1 = 'b'; // or window.mname1 = 'b';
mname2 = 'c'; // etc.
mname3 = 'd';
mname4 = 'e';

for (var i = 0; i < mlength; i++) {
    alert (window['mname'+i]);
}

Remember, polluitng the global namespace is a bad practice, unless you really need to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM