如何在函数外部获取数组的所有内容?
$.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"
}
]
答案 0 :(得分: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
答案 1 :(得分: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;