-3

如何在函数之外获取数组的所有内容?

 $.each(Basepath.Templates, function(i){
     templateArray = new Array({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, description: Basepath.Templates[i].Template.name});
});

console.log(templateArray); //contains only one array;

编辑:

这是我想要的输出

templateArray[
    {
        title: "one",
        src: "view/1",
        description: "Descrption 1"
    },
    {
        title: "two",
        src: "view/2",
        description: "Descrption 2"
    },
    {
        title: "one",
        src: "view/3",
        description: "Descrption 3"
    }
]
4

2 回答 2

3

尝试在调用之前为数组设置变量,.each()并在每次迭代时添加到数组中。

var templateArray = [];
$.each(Basepath.Templates, function(i){
    templateArray.push({title: Basepath.Templates[i].Template.name, src: 'view/'+Basepath.Templates[i].Template.id, description: Basepath.Templates[i].Template.name});
});

console.log(templateArray); //should work
于 2012-05-21T02:19:39.970 回答
2

templateArray在每次迭代中都覆盖。尝试.map()代替each()

var templateArray = $.map(Basepath.Templates, function(tpl, i){
    return {
        title: tpl.Template.name,
        src: 'view/'+tpl.Template.id,
        description: tpl.Template.name
    };
});
console.log(templateArray); // now is only one array, containing template objects;
于 2012-05-21T02:32:33.367 回答