javascript - 从函数返回数组并将其分配给变量

标签 javascript jquery arrays

我试图从函数返回一个对象数组并将其分配给变量

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;
        }
    });
};

现在我尝试像这样分配它

var contactsarray =contactsbuilder(customdetails.contacts);

但是即使在控制台日志生成之后,contactsarray 也始终保持未定义状态。我尝试了 setTimeout 但没有成功

我尝试了一个更简单的没有 foreach 的方法

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

现在有些东西获取了数组值,我的情况出了什么问题?

最佳答案

您需要在 each() 回调中返回数组,这没有任何效果。 contactsbuilder 函数没有返回任何内容,因此将 return 语句移到外部。

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
};

关于javascript - 从函数返回数组并将其分配给变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37298288/

相关文章:

javascript - jQuery 验证在 Bootstrap 模式中不起作用

javascript - 清除数组中一项的超时 - javascript

javascript - Google 表单提交页面

javascript - 如何在nodejs中将字符串转换为Uint8Array类型

javascript - 根据值数组中的值查找对象数组中的对象 - Javascript

jquery - 定义Content-Type时跨域jQuery AJAX失败

javascript - JS : nvmrc vs package. json 引擎?

jquery - magicsuggest 的 CSS 问题

java.lang.IndexOutOfBoundsException异常

javascript - 如何按数组成员求和