【问题标题】:jQuery return all Array [closed]jQuery返回所有数组[关闭]
【发布时间】:2012-05-21 02:17:14
【问题描述】:

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

 $.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"
    }
]

【问题讨论】:

  • templateArray = new Array 当然是一个数组有什么问题?
  • 总之,它太本地化了

标签: javascript jquery arrays


【解决方案1】:

尝试在.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

【讨论】:

  • 很好的发现数组被覆盖了。
  • 我在函数之前设置了变量,但它仍然返回一个数组。谢谢,
【解决方案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;

【讨论】:

  • 感谢它有效!它保存了我的项目! :D
  • @gdoron:我会吗?我没有编码$(array).map(iterator).get()
  • 不,你是对的。我从来没有这样用过map
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多