$ .Each output back in jQuery

I make a little secret tool. The result will be in the table, and on the left side I would like to list the numbers that I saved in $.each() . So here is my code:

 $.each([1,2,3,4,5], function(i, l){ var lol = (some math stuff here); $("#output").append("<tr><td>" + l + "</td><td>" + lol + "</td><tr>"); }); 

What this means is the following:

 1. lol1 2. lol2 3. lol3 4. lol4 5. lol5 

What I'm trying to do is change the value of l , but leave everything else alone so that the result looks like this:

 5. lol1 4. lol2 3. lol3 2. lol4 1. lol5 
+4
source share
7 answers

Create a copy of the array and then modify it. Here is a working example: http://jsfiddle.net/naRKF/

And the code (HTML is not the same as yours, but the JS method is what you should focus / use):

 var arr1 = [1,2,3,4,5]; var arr2 = arr1.slice().reverse(); //creates a copy and reverses it var html = ''; for(var i = 0; i < arr1.length; i++){ html += '<div>' + arr2[i] + '.' + ' lol' + arr1[i] + '</div>'; } $('body').append(html); 
+9
source

$.each() will always $.each() over the array in the correct order. You want to use a for loop for this, not jQuery $.each() .

+2
source
 x = [1,2,3,4,5] $.each(x.reverse(), function(i, l){ var lol = (some math stuff here) $("#output").append("<tr><td>" + l + "</td><td>" + lol + "</td><tr>") }) 
+2
source

Try the following:

 $.each([1,2,3,4,5].reverse(),function(i,l){... 

Basically, since you are using your own array, you can simply undo it to go in the opposite direction.

+1
source

Here you go

 var arr = [1,2,3,4,5]; var counter = arr.length $.each(arr, function(i, l){ var lol = "lol"+l; $("#output").append("<tr><td>" + counter-- + ".&nbsp;&nbsp;</td><td>" + lol + "</td><tr>"); }); 

Job demonstration

+1
source
 var a=[1,2,3,4,5] $.each(a, function(i, l){ var lol = (some math stuff here); $("#output").append("<tr><td>" + a[a.length-i] + "</td><td>" + lol + "</td><tr>"); }); 
0
source

This may help the following:

 function test(arr) { if ($.isArray(arr)) { var reverse = arr.slice().reverse(); $(arr).each(function(i) { console.log(reverse[i] + ". lol" + this); }); } } test([1, 2, 3, 4, 5]); 
0
source

Source: https://habr.com/ru/post/1386722/


All Articles