Javascript数组返回undefined

时间:2011-11-07 15:40:43

标签: javascript arrays return return-value undefined

我目前正在将一个javascript文件链接到一个html页面,并且在使用该javascript文件中的函数时,返回值基本上被删除并显示为未定义,即使在函数本身中定义了值(可能是非常混乱,我只是展示代码,它应该有意义):

functions.js

function addActivity(contactNameSelected, username) {   
var returnArray = [];
//post to .php
        if(data.added)
        {
            var newEvent = [];
            newEvent['id'] = data.id;
            newEvent['date'] = formattedDate;
            returnArray.push(true);
            returnArray.push(newEvent);
            return returnArray; //when i debug, this has a value and is a valid array at this point
        }
        else
        {
            returnArray.push(false);
            returnArray.push(data.message); //when i debug, this has a value and is a valid array at this point
            return returnArray;
       }
    }

home.html的

var response = [];
response = addActivity(contactNameSelected, username); //although valid above, undefined here
if(response[0]) //error b/c response is undefined
{
    //do stuff if successful 
}
else{
    //do other stuff if unsuccessful
}

如果我只是返回一个字符串它工作正常,但由于某种原因,如果我尝试返回一个数组,它只是未定义。这是为什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

我猜测省略的'//post to .php'看起来像

$.post('...php', { ... }, function(data) {
   if (data.added) ...

AJAX响应由回调函数处理,它以异步方式执行。换句话说,returnArrayaddActivity返回后填充return returnArray;

addActivity语句无用,因为您从回调返回值,而不是从function addActivity(contactNameSelected, username, callback) { $.post('...', { ... }, function(data) { var returnArray=[]; if(data.added) { ... } else { ... } callback(returnArray); }); } 返回。回调不是由您的代码调用,而是由XHR(在不同的执行上下文中)调用,并且其返回值将被丢弃。

要以异步方式正确传回数据,我们需要调整您的代码。

addActivity(contactNameSelected, username, function(response) {
    if(response[0])
    {                                
        ...
    }                                
    else
    {                                
        ...
    }
});

{{1}}