简体   繁体   中英

returning array from function and assigning it to variable

I am trying to return an object array from a function and assign it to a variable

function contactsbuilder(contacts){
    var contactsarray = [];
    parent.$(contacts).each(function(i,contact){
        contactsarray.push(somevalues);
        if(contacts.length == i+1){
            console.log("coming in here?");
            return contactsarray;
        }
    });
};

Now I tried to assign it like

var contactsarray =contactsbuilder(customdetails.contacts);

but contactsarray always stays undefined even after the console log is made. I tried setTimeout but no luck

I tried a simpler one without foreach

function sample(){
var xx= ["ss","ssdfds"];
return xx;
}
var something = sample()

Now something gets array value, what is wrong in my case?

You need to returning the array inside the each() callback which doesn't have any effect. And nothing is returning from the contactsbuilder function, so move the return statement outside.

function contactsbuilder(contacts){
    var contactsarray = [];
    parent.$(contacts).each(function(i,contact){
        contactsarray.push(somevalues);
        if(contacts.length == i+1){
            console.log("coming in here?");
        }
    });
    return contactsarray;// return the array
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM