簡體   English   中英

如何使用javascript中的for循環成對檢索數組元素?

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

我創建了一個空數組,網站用戶必須使用輸入表單來填充它。 用戶可以輸入他/她想要的任意數量的元素(在這種情況下為朋友),但總數必須為偶數。 在數組中使用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 "

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM