0

Need a proper solution how to write this expression.

var ary1 = ["","",""];
var ary2 = ["","",""];
var ary3 = ["","",""];
var ary4 = ["","",""];
var div;
for(var i=1; i<5; i++){
    div += ("<p id='text'"+i+">"+(ary+i)[0]+"</p>");
}

Just looking for a better solution to make it work. Not getting value from ary1, ary2, ary3 and ary4.

djot
  • 2,952
  • 4
  • 19
  • 28
fguru
  • 71
  • 2
  • 9

4 Answers4

3

If you'd like to reference the different arrays in such a manner, storing them in an object would be a very elegant solution.

var arrayDictionary = {
  ary1: ["","",""],
  ary2: ["","",""],
  ary3: ["","",""],
  ary4: ["","",""]
};
for(var i=1; i<5; i++){
    div += ("<p id='text'"+i+">"+ arrayDictionary["ary"+i][0]+"</p>");
}
stinkycheeseman
  • 43,437
  • 7
  • 30
  • 49
0
var ary1 = ["","",""];
var ary2 = ["","",""];
var ary3 = ["","",""];
var ary4 = ["","",""];
var div;
for(var i=1; i<5; i++){
    div += ("<p id='text'"+i+">"+eval('ary'+i '[0]')+"</p>");
}
  • 2
    Be wary of using `eval`, as it can be dangerous and is generally [inefficient](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – stinkycheeseman Oct 16 '13 at 17:39
  • Can you explain why it can be dangerous and inefficient ? – To delete profile Oct 16 '13 at 17:42
  • Sure thing! [Here is a concise explanation](http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea) - [here is an explanation of how it can be used properly](http://www.nczonline.net/blog/2013/06/25/eval-isnt-evil-just-misunderstood/) - and [here you can read about how it's crazy](http://wingolog.org/archives/2012/01/12/javascript-eval-considered-crazy) – stinkycheeseman Oct 16 '13 at 19:14
0

Try an array of arrays:

ary = [
  ["","",""],
  ["","",""],
  ["","",""],
  ["","",""]
];

var div = '';
for (var i = 0, len = ary.length; i < len; i++) {
    div += "<p id='text'" + i + ">" + ary[i][0] + "</p>";
}
bozdoz
  • 12,550
  • 7
  • 67
  • 96
0

why not use 2D array?

    arr=[ary1,ary2,ary3,ary4,ary5];

for(var i=1; i<arr.legnth; i++){
  for (var j=1;j<arr[i].length;j++){
    div += ("<p id='text'"+j+">"+arr[i][j]+"</p>");
  }
}
zzxx53
  • 413
  • 3
  • 12