I have a $each(array, function()); and within that statement, i have afor loop , Is it safe to be doing this? and could this be the reason that i am getting the same values multiple times returned even though the object array length is 8, i am getting basically doubled up results, sometimes its more. if you need to see my code, i can post it.

4 Weeks
Discussion Span
Last Post by pty

Your for loop will be executed once per iteration of your $.each loop.

If that's what you intend to do, then it's not dangerous. Perhaps posting an example of your code (use jsfiddle or similar) would help you explain exacctly what your concerns are.

Additionally, the two types of loop can be used for the same purpose, they are just different syntax (there are other differences but let's not complicate things).

Edited by pty


A few points.

You are looping through dutyStatusLogs multiple times in different ways. You're calling dutyStatusLogs.forEach twice and $.each(dutyStatusLogs, function(i,v){...}) once. These should probably be combined into one loop.

Now, what your original question was about, the nested loop

        $.each(dutyStatusLogs, function(index, value) {

                    var json = dutyStatusLogs;

                        var tr;
               for (var i = 0; i < json.length; i++) {

This section doesn't look right to me. You don't appear to be using the outer loop for anything (there are no references to index or value inside the $.each loop), and you're executing the inner loop once per iteration.

I would rewrite that section in the following manner:

$.each(dutyStatusLogs, function(index, dsl) {
    var dateFieldValue = dsl.dateTime;
    var employeeNo = dsl.driver.employeeNo ;
    var status = dsl.status;


Note I'm using variable dsl (for dutyStatusLog) instead of accessing the original array with the index, this is one of the benefts of using jQuery's $.each function. Newer JavaScript allows for an even simpler syntax. If that's an option you can make your code more readable by using it.

for (variable of iterable) {
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.