steve Kim steve Kim - 2 months ago 7
Javascript Question

jquery perform another function in last "for" run

I have js objects and a function as follow:

function my_function(data){
var cont = [];
for (var i = 0; i < (data.length); i++) {
var info = data[i];
var r_id = info['ID'];
cont.unshift(r_id); //example: [12,158,125,126,126]
};
//I need to save the last id (in this case, 126) as `saved_id` to be used in another function
};

var saved_id;


Now, I need to save the last number (in this case, 126) as a separate variable (as
saved_id
) to be used in another function.

How would I do this so that when the
for
function runs and if it is the last run, then it performs another function (in this case, updates the
saved_id
variable with the last id number)?

Answer
var saved_id;
function my_function(data){
    var cont = []; 
    for (var i = 0; i < (data.length); i++) {                   
       var info     = data[i];  
       var r_id     = info['ID'];
       cont.unshift(r_id);  
       saved_id = r_id;//update saved_id every time last value will be in it when loop ends
    };  

};  
Comments