如何使用javascript中的for循环成对检索数组元素

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

本文关键字:检索 数组元素 循环 for 何使用 javascript 中的      更新时间:2023-09-26

我创建了一个空数组,该数组必须由网站用户用输入表单填写。用户可以输入他/她想要的任何数量的元素(在本例中是朋友),但总数必须是偶数。在数组中使用sort()方法(打乱输入设置的初始顺序)后,我需要与它的元素成对,并将其打印在网站上。我尝试使用for循环来完成此操作,但一次只能检索一个元素。有办法吗?提前感谢!

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使动态创建对象变得非常简单,您可以执行以下操作:

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 "