简体   繁体   中英

javascript how to pass each element in an array to different var

I am new to javascript and recently have a problem to passing elements from array to var.

For example, I have an array like var anArray = [[a1,a2,a3],[b1,b2,b3],[c1,c2,c3]], and I have 3 different var a , b and c.

after some loop codes,

what I would like to see is:

while a=a1, b should be b1 and c=c1

while a=a2, b=b2 and c=c2

while a=a3, b=b3, c=c3

also pls consider that what if I have array like:

[[a1,a2,a3],[b1,b2,b3]] which will result a=a1 while b=b1, a=a2 while b=b2 etc.

or [[a1,a2],[b1,b2],[c1,c2]] which will result a=a1 while b=b1 and c=c1, a=a2 while b=b2 and c=c2

If my question is still not clear enough, please comments it and I will update it.

I really appreciate all the comments and the code that you have made! Many thanks!

You have a bunch of pieces backwards and in the wrong place:

var anArray = [[1,2],[1,2]]; 
for(var i=0;i <= anArray.length - 1;i++)
{
    for(var j=0;j<anArray[i].length;j++){
        var a = anArray[i][j];
        var b = anArray[i + 1][j];
        alert("a: "+a+" and b: "+b);
    }

}

Edit: adjusted after you changed your entire question.

After you clarified your question I got a general idea of what you want. I think this is what you want to achieve. The example is dynamic so that as long as the length of item in the array is equal.

  var anArray = [[1,2,3],[4,5,6],[7,8,9]]; for(var j=0;j<anArray[0].length;j++){ var values = []; for(var i=0;i<anArray.length;i++) { values[i] = anArray[i][j]; } //Do what you want with the values below. I chose to show them in a alert message var text = ''; for(var i=0;i<anArray.length;i++) { if(text.length>0){ text += ',' }; text += values[i]; } window.alert('Values: ' + text); } 

PS: There were not 1 but a few things wrong with your code.

Let say that we have have an array like this var anArray = [[1,2,3],[4,5,6]]; and if you want to alert this a=14;b=25;c=36; then you can use this code

var anArray = [[1,2,3],[4,5,6]];
for ( i = 0; i < anArray.length; i++ ) {
    var  l = anArray[i];
    for ( m = 0; m < l.length; m++ ){
        this["a"+i+m.toString()] = l[m];
    }
}
alert("a = "+ a00 + a10.toString());
alert("b = "+ a01 + a11.toString());
alert("c = "+ a02 + a12.toString());

Where a00=1; a01=2; a02=3; these are the elements of the first array.(the middle nr. tells the array so for the first array we use 0). Then we have a10=4; a11=5; a12=6; these are the elements of the 2nd array.(the middle nr. tells the array so for the second array we use 1).

All you have to do is just replace this array var anArray = [[1,2,3],[4,5,6]] with yours and let javascript do its job.

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