JavaScript返回数组对象

时间:2014-01-17 00:13:10

标签: javascript jquery

我正在尝试将json数组返回给函数并输出结果。这是我想要实现的一个例子,但'thisArray'一直是'undefined'。我究竟做错了什么?感谢反馈...

<html>
<head>
<title>Test Array</title>

   

function recipesTestObject(recId, recipe)
{
 this.recId = recId;
 this.recipe = recipe;

}

function initialise() {


    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", { recCategory: 2 }, function(json) {
         var recipeTest = new Array();
        $.each (json.recipes, function (){

         recipeTest[recipeTest.length] = new recipesTestObject(this['id'], this['recName']);


        });

     return recipeTest; 

    });


   }

    function display(thisArray) {

for (var i=0; i < thisArray.length; i++) {
    document.write("Name: "+thisArray[i].recipe+"<br>");

}

    }
   </script>
   </head>
<body>
<script language="javascript">

var x;

x = initialise();

display(x);
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

您在成功回调函数中返回它,但不是从初始化函数返回。

有很多方法,一个是使用回调:

function initialise(callback) {

    $.getJSON ("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", 
    { recCategory: 2 }, function(json) {
        var recipeTest = [];
        $.each (json.recipes, function (){
            recipeTest.push(new recipesTestObject(this['id'], this['recName']));
        });
    callback(recipeTest);
    });
}

然后你这样称呼它:

initialise(display);

答案 1 :(得分:0)

thisArrayundefined,因为initialise未返回值。

您可以使用回调函数来解决此问题:

function initialise(callback) {
    $.getJSON("/mealplanners2/apprequests/mealplanner.php?action=getRecipesByCat", {
        recCategory: 2
    }, function (json) {
        var recipeTest = [];
        $.each(json.recipes, function () {
            recipeTest.push(new recipesTestObject(this.id, this.recName));
        });
        callback(recipeTest);
    });
}

然后而不是

var x;
x = initialise();
display(x);

你可以这样做:

initialize(display);

请注意,我使用的是[]而不是new Array()。这是初始化数组的首选方法。

我还使用recipeTest.push(...)代替recipeTest[recipeTest.length] = ...,因为push是将项目添加到数组的首选方法。

您也可以this.id代替this['id']

相关问题