dimanche 28 octobre 2018

If else/ for loops in JavaScript

Is there any way to make this if-else loop generalized. Right now the truthArray consists of values from t1 to t4. I am looking for a way to create a generalized solution for any number of values t5, t6 and so on. I am not getting how to tell the for loop to create more and more nested if statements depending on the lenght of the truth array. Thanks.

var truthArray = [t1, t2, t3, t4]; 
            var positionArray = [];
            var offsetArray = [];
            var i;        
  
           
            if (truthArray[0] === true) {
                positionArray[0] = 'left';
                offsetArray[0] = 0;
                if (truthArray[1] === true) {
                    positionArray[1] = 'right';
                    offsetArray[1] = 0;
                    if (truthArray[2] === true) {
                        positionArray[2] = 'left';
                        offsetArray[2] = 60;
                        if (truthArray[3] === true) {
                            positionArray[3] = 'right';
                            offsetArray[3] = 60;
                        }
                    }
                    else if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                        offsetArray[3] = 60;
                    }
                }
                else if (truthArray[2] === true) {
                    positionArray[2] = 'right';
                    offsetArray[2] = 0;
                    if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                        offsetArray[3] = 60;
                    }
                }
                else if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                    offsetArray[3] = 0;
                }
            }
            else if (truthArray[1] === true) {
                positionArray[1] = 'left';
                offsetArray[1] = 0;
                if (truthArray[2] === true) {
                    positionArray[2] = 'right';
                    offsetArray[2] = 0;
                    if (truthArray[3] === true) {
                        positionArray[3] = 'left';
                        offsetArray[3] = 60;
                    }
                }
                else if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                    offsetArray[3]   = 0;
                }
            }
            else if (truthArray[2] === true) {
                positionArray[2] = 'left';
                offsetArray[2] = 0;
                if (truthArray[3] === true) {
                    positionArray[3] = 'right';
                    offsetArray[3] = 0;
                }
            }
            else if (truthArray[3] === true) {
                positionArray[3] = 'left';
                offsetArray[3] = 0;
            }
            

Aucun commentaire:

Enregistrer un commentaire