Search code examples
javascriptcasperjs

The values of the array after the loop are lost


The values ​​of "end" after the loop are lost and I do not understand the reason.

var horas = ['2','6']
var x6 = ['1','2','3','4','5','6','7']
var x5 = ['uno','dos','tres','cuatro','cinco','seis','siete']
var final = [];		
   for (var i = 0; i <= x6.length; i++) 
   {

    if(x6[i].indexOf(horas[0])!==-1) {final.push(x5[i]);}
    if(x6[i].indexOf(horas[1])!==-1) {final.push(x5[i]);}
    if(x6[i].indexOf(horas[2])!==-1) {final.push(x5[i]);}
	 console.log(final); // here yes exists
    }			

    console.log(final); // does not exists, Does not show anything


Solution

  • You need to keep the index inside of the array.

    for (var i = 0; i < x6.length; i++) {
    //                 ^
    

    var horas = ['2', '6']
    var x6 = ['1', '2', '3', '4', '5', '6', '7']
    var x5 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete']
    var final = [];
    for (var i = 0; i < x6.length; i++) {
        if (x6[i].indexOf(horas[0]) !== -1) { final.push(x5[i]); }
        if (x6[i].indexOf(horas[1]) !== -1) { final.push(x5[i]); }
        if (x6[i].indexOf(horas[2]) !== -1) { final.push(x5[i]); }
        console.log(final);
    }
    
    console.log(final);

    A more concise version with a switched Array#indexOf part.

    var horas = ['2', '6'],
        x6 = ['1', '2', '3', '4', '5', '6', '7'],
        x5 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis', 'siete'],
        final = [],
        i;
    
    for (i = 0; i < x6.length; i++) {
        if (horas.indexOf(x6[i]) !== -1) {
            final.push(x5[i]);
        }
    }
    
    console.log(final);