[英]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.
在数组中使用sort()方法(以打乱由输入设置的初始顺序)之后,我需要与其元素形成对并在站点上打印出来。 I tried to do this using the for-loop but I can only retrieve one element at once.
我尝试使用for循环来执行此操作,但一次只能检索一个元素。 ¿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 : 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.