-2

So my problem is I have 2 declared arrays inside a function. Each time I call this function, it removes one item from both arrays. The next time I call the function, the elements is deleted before it remains.

Now I know where the problem is.I know I'm declaring the same arrays in a function call, but what I want is to make those arrays static, and I know if I declared the 2 arrays outside the function it will work out perfectly.

BUT I'm forced to let those arrays declared inside the function. So is there any way I can do this please ? Here's my code:

function Tirage(){
  var Binomes=['George','Davide','Anna','Martin','Lucy','Nancy'];
  var Projet=['Foundation','Skeleton','Bootstrap','UIkit','Base','W3.CSS'];

  var c1=parseInt((Math.random())*(Binomes.length));
  var c2=parseInt((Math.random())*(Projet.length));

  Binomes.splice(c1,1);
  Projet.splice(c2,1);

  alert(c1+"\n"+Binomes);
  alert(c1+"\n"+Projet);

}

EDIT the initial code is this, and i'm not allowed to change it or have other code outside the function:

function Tirage(){
     var Binomes=['George','Davide','Anna','Martin','Lucy','Nancy'];
     var Projet=['Foundation','Skeleton','Bootstrap','UIkit','Base','W3.CSS'];

     //Complete Code here
}

Edit 2

Seems like the question isn't understandable wich is my fault, so the exercise wants me to create a Randomly Drawing and insert what i draw in rows inside a table. The function that will do this have inside of it 2 decalred Arrays and i have to Draw randomly one element from each array, and insert it as a row with 2 cellules, inside a table.

Because i didn't read the exercise well, i thought that the function only draws once in each function call, meaning that if i click the first time i'll only draw once and insert that draw in the table, then the second time the same thing but with avoiding to draw what is already being inserted in the table.

I'm sorry for that, and the original question is already answer bellow

hamza saber
  • 511
  • 1
  • 4
  • 18
  • You can use `this.Binomes` and `this.Projet` instead of declaring the variables. Just check if the arrays does not exist at the beginning, in which case you create them. – Seblor Jan 01 '19 at 12:33
  • 1
    `BUT i'm forced to let those arrays declared inside the function` Can you elaborate on this requirement? Could you use an IIFE, for example? – CertainPerformance Jan 01 '19 at 12:35
  • Use a [closure (MDN)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) -> [How do JavaScript closures work?](https://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – Andreas Jan 01 '19 at 12:36
  • @CertainPerformance the homework i have says i have to complete the code and they've put the two arrays inside the function – hamza saber Jan 01 '19 at 13:50
  • 1
    which part is the assignment about? what is the learning part of this assignment? – Nina Scholz Jan 01 '19 at 14:11
  • @NinaScholz ok the homework is that the first array presents the students and the 2nd array present the frameworks that the student have to work with. My job is when i click a button i need to assign randomly a framework to a student until there's nothing left in the arrays, without changing the initial code and without adding any code outside the function. What i thought and implementing it right now is that each time i call the function i must first delete the elements from the 2 arrays that i already used. – hamza saber Jan 01 '19 at 14:21
  • What should the function *return*? – trincot Jan 01 '19 at 14:28
  • @trincot nothing – hamza saber Jan 01 '19 at 14:32
  • 1
    So how will you then know which pairs have been made? Is the task really to use `alert` for that? That really does not sound like a good programming exercise... Is the exercise available on a public site? Even if in French, could you provide the link to it, so we can read the whole context? – trincot Jan 01 '19 at 14:33
  • yeah what i have to do is to insert a row in a table. sure here's the link for the file its Exercice 3 http://www.mediafire.com/file/p5i2jq9wu4921yb/CC_2016-2017.pdf/file – hamza saber Jan 01 '19 at 14:44
  • 1
    Using global (in the sense of "outside the function") variables is the right approach here, the requirement your teacher made is missleading. – Jonas Wilms Jan 01 '19 at 15:28
  • @hamzasaber, I have updated my answer based on that document. You should really include the question as it is asked in that document. It is important that it says (translated) *"Below you'll find how the page `index.html` looks before and after the click on the button 'Start'"*. That makes it clear that the 6 attributions should happen all with one click, and so you don't need any "static" variable. It all happens locally in the function. – trincot Jan 01 '19 at 16:09

3 Answers3

1

Seeing exercise 3 of the document you link to in comments, I note that you are asked to write a function that will make all the connections at once, requiring only one call to the function. And it should populate a table.

In that case proceed like this:

function Tirage() {
    var Binomes=['George','Davide','Anna','Martin','Lucy','Nancy'];
    var Projet=['Foundation','Skeleton','Bootstrap','UIkit','Base','W3.CSS'];

    // Get a reference to the table 
    var table = document.getElementById("IADO");
    // Remove the tbody element if it exists. This is to remove the previous result if there is one.
    if (table.children.length > 1) table.removeChild(table.children[1]);
    // Regenerate a new tbody element
    var tbody = table.appendChild(document.createElement("tbody"));
    
    while (Binomes.length && Projet.length) {
        var c1 = Math.floor(Math.random() * Binomes.length);
        var c2 = Math.floor(Math.random() * Projet.length);
        // Add the corresponding 2 values as a pair in the output array:
        var row = tbody.insertRow(-1);
        var cell = row.insertCell(-1);
        cell.textContent = Binomes.splice(c1,1)[0];
        cell = row.insertCell(-1);
        cell.textContent = Projet.splice(c2,1)[0];
    }
}
.CSSTableGenerator { width: 100% } 
<fieldset>
    <legend>Master</legend>
    <fieldset>
        <legend><button onclick="Tirage()">Start</button></legend>

        <table id="IADO" style="border-collapse: collapse;" class="CSSTableGenerator">
            <thead><!-- header of the table -->
                <tr style="border: 1px solid black;">
                    <th style="border: 1px solid black;">Name</th>
                    <th style="border: 1px solid black;">Framework</th>
                </tr>
            </thead>
        </table>
    </fieldset>
</fieldset>

Side note: please don't use parseInt on something that is already a number. It will make the number a string and then the string a number again. Use Math.floor instead.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • Thank you so much for the comment above. I didn't notice actually that i have to do the Draw all at once. But i've done the exercise in case we want to Draw one element from the 2 arrays each time we click the button. i'll add it below, it may help someone else. – hamza saber Jan 01 '19 at 22:10
0

It depends what your context currently is. If your context this is an instance of some class then you could simply add your array as a property of your instance.

However, I'll be assuming that you're not in an instance and thus this would probably refer to window object.

function Tirage() {
  if (!window.Binomes && !window.Project) {
    console.log("in");
    window.Binomes = ['George', 'Davide', 'Anna', 'Martin', 'Lucy', 'Nancy'];
    window.Projet = ['Foundation', 'Skeleton', 'Bootstrap', 'UIkit', 'Base', 'W3.CSS'];

  }

  const {Binomes, Projet} = window;

  var c1 = parseInt((Math.random()) * (Binomes.length));
  var c2 = parseInt((Math.random()) * (Projet.length));

  Binomes.splice(c1, 1);
  Projet.splice(c2, 1);

  console.log(c1 + "\n" + Binomes);
  console.log(c2 + "\n" + Projet);
  console.log("Remaining Length: " + Binomes.length + ", " + Projet.length);
}

setInterval(Tirage, 1000);
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
0

The solution I propose here may be a bit confusing. It seems to even answer the problem raised here because we want to go on the option of wanting to put all the code in the function that does the action. Obviously, the two variables Tirage.arrayC1 and Tirage.arrayC2 are global variables but they are declared inside the function and are within reach of our function.

The condition that verifies if they are not worth undefined makes it possible precisely not to lose their values to the various executions of the function.

The first time the function will be called they will definitely be "undefined" and it will be the perfect time to declare them and to have an empty board.

I hope this helps you.

function Tirage(){
  if(Tirage.arrayC1 == undefined || Tirage.arrayC2 == undefined){
   Tirage.arrayC1 = [];
    Tirage.arrayC2 = [];
  }
  var Binomes=['George','Davide','Anna','Martin','Lucy','Nancy'];
  var Projet=['Foundation','Skeleton','Bootstrap','UIkit','Base','W3.CSS'];
  
  var c1=parseInt((Math.random())*(Binomes.length));
  var c2=parseInt((Math.random())*(Projet.length));
  
  Tirage.arrayC1.push(c1);
  Tirage.arrayC2.push(c2);
  
  for(var i=0; i<Tirage.arrayC1.length;i++){
    Binomes.splice(Tirage.arrayC1[i],1);
    Projet.splice(Tirage.arrayC2[i],1);
  }
  
  console.log(Binomes);
  console.log(Projet);
}



Tirage();
Tirage();
Tirage();
Tirage();
Tirage();
Tirage();
Tirage();
Tirage();
soumare
  • 394
  • 5
  • 9