mike
mike

Reputation: 35

javascript for loop with 2 arrays

This is what I'm trying to accomplish:

var result = document.getElementById("o_q1_op1");
document.getElementById("a1_op1").style.height = result.scrollHeight;

But I dont want to rewrite it a dozen times, instead want to use arrays structured like this:

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];

This is what I have so Far:

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];
var result;
var index;
var text = "";
for (index = 0; index < que.length; index++) {
    text += que[index];
    var result[index] = document.getElementById(text);
}

var index2;
var text2 = "";
for (index2 = 0; index2 < ans.length; index2++) {
    text2 += ans[index2];
    document.getElementById(text2).style.height = result[index].scrollHeight;
}

I'v never used 2 arrays to accomplish one task before so I'm not sure how to go about it.

Upvotes: 0

Views: 50

Answers (3)

Jamiec
Jamiec

Reputation: 136239

You might like to not use 2 arrays, and instead have one array that ties the two properties together:

var arr = [
             { q:"o_q1_op1",a:"a1_op1"},
             { q:"o_q1_op2",a:"a1_op2"}
          ];

and then the code becomes much simpler, and you never have to deal with the 2 arrays becoming different lengths

for(var i=0;i<arr.length;i++){
    var result = document.getElementById(arr[i].q);
    document.getElementById(arr[i].a).style.height = result.scrollHeight;
}

Upvotes: 3

Radio
Radio

Reputation: 2863

So long as the two arrays are ordered and remain the same length...

for(var i=0;i< que.length;i++){
    document.getElementById(ans[i]).style.height = 
    document.getElementById(que[i]).scrollHeight;
}

Upvotes: 1

john Smith
john Smith

Reputation: 17936

well the += is wrong because it concatinates string

change and simplify code to

var que = ["o_q1_op1", "o_q1_op2", "o_q2_op3"];
var ans = ["a1_op1","a1_op2","a1_op3","a1_op4"];
var result=[];

for (var index = 0; index < que.length; index++) {
    result[index] = document.getElementById(que[index]);
}


for (var index2 = 0; index2 < ans.length; index2++) {
    document.getElementById(ans[index2]).style.height = result[index].scrollHeight;
}

Upvotes: 1

Related Questions