dimanche 15 août 2021

How the variable is defined in the nested loop? [closed]

I have here an array called pets

  const pets = [
    "cat: Smith, Meowsalot",
    "young dog: Jones, Barksalot",
    "rabbit: Doe, Fluffy"
];

i want the output to be ""the animal name" "the animal kind" in seperated lines using RegEx. for example :

Smith Meowsalot cat
Jones Barksalot young dog

So i used nested loop in order to get that the regex works just fine :

let re = /(.+(?=:)):\s((?<=:\s).+),\s(.+)/i

then the nested for loop

let arr = [];
for (let i = 0; i < 3; i++) {
    let test = re.exec(pets[i])
    arr[i] = [];
    

    for (let j = 2; j >= 0; j--) {

        arr[i][j] = test[j + 1]
        if (j != 0) {
            document.querySelector('#app').innerHTML += ` ${arr[i][j]} `
        }

    }
   
    if (j = 2) {
        console.log("j is", j)
        document.querySelector('#app').innerHTML += ` ${arr[i][0]} </br>`
    }
}`

It worked fine but i dont understand how J is defined outside the sub-loop "where it is used". and i don't undesrstand why if i inserted the second if statment to the sub-loop (J) it will be infinite.

Aucun commentaire:

Enregistrer un commentaire