简体   繁体   中英

How do I retrieve array elements in pairs using the for loop in javascript?

I created an empty array which has to be filled by the website user with the input form. The user can input any number of elements (in this case, friends) he/she wants, but the total has to be an even number. After using the sort() method in the array (to shuffle the initial order set by the input), I need to form pairs with its elements and print it on the site. I tried to do this using the for-loop but I can only retrieve one element at once. ¿Is there a way to do it? Thanks in advance!

var lista = [];

function muestraNombres(){
    var x = $("#amigo").val();

    if(x == ""){
        alert("ingresa bien los datos");
    }else{
        lista.push(x);

       $("#listado").append('<div id="otrodiv">' + x + '</div>');
       $("#amigo").val('');
    }
}


function recuperaNombres (){
    if (lista.length%2 != 0) {
        alert("Debes ingresar otro amigo para realizar los pares");
    }else{
        amigoSecreto();
    }
}

function amigoSecreto(){
    $("#listado").hide();
    shuffle();
    generaPares();
}

function shuffle (){
    lista.sort(function() {return 0.5 - Math.random() })
}

function generaPares (){
    for (var i=0; i<lista.length;i++){
        $("#resultado").append('<div id="otrodiv1">' + lista[i] + '</div>')
    }
    $("#reiniciar").show();
    $("#parear").hide();
    $("#ingresar").hide();
}
for (var idx=0; idx < arr.length; idx += 2) {
    arr[idx]; // is first element in pair
    arr[idx+1]; // is second element in pair
}

Javascript makes it very simple to create objects on-the-fly, you can do something like this :

var friendsArray = [];

// let's put some values in the array
// using plain simple object notation
friendsArray.push( { name : 'stan', friendName : 'kyle' } ) ;  
friendsArray.push( { name : 'stan', friendName : 'eric' } ) ;
friendsArray.push( { name : 'butters', friendName : 'kenny' } ) ;

// let's print the array
for (var i=0; i<friendsArray.length; i++) {
    var thisFriend = friendsArray[i];
    console.log(thisFriend.name + ' has ' + thisFriend.friendName + ' as a friend ');
}

// output is :
// "stan has kyle as a friend "
// "stan has eric as a friend "
// "butters has kenny as a friend "

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM