我想返回一个json数组到一个函数并输出结果。以下是我想要实现的一个示例,但是'thisArray'会以'未定义'的形式出现。我究竟做错了什么?感谢反馈...JavaScript返回数组对象
<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>
除了重复之外,一旦你解决了异步问题,你会发现你不应该使用'document.write()',因为它会在页面加载后被调用。 –