循环后数组的值丢失

The values of the array after the loop are lost

循环后"end"的值丢失,不明白原因

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

您需要将索引保留在数组中。

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);

一个更简洁的版本,切换了 Array#indexOf 部分。

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);

Problem in array index while iterating the loop

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

should be changed to

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