Javascript 获取JSON对象数组中的值

Javascript 获取JSON对象数组中的值,javascript,arrays,json,loops,Javascript,Arrays,Json,Loops,我有一个JSON对象数组,如下所示: [ { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" }, { name: "tom", text: "tasty" } ] 我想循环浏览它们,并在列表中重复它们。我怎么做呢?你是说这样的事 var a = [

我有一个JSON对象数组,如下所示:

[
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]

我想循环浏览它们,并在列表中重复它们。我怎么做呢?

你是说这样的事

 var a = [
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" },
     { name: "tom", text: "tasty" }
 ];

 function iter() {
     for(var i = 0; i < a.length; ++i) {
         var json = a[i];
         for(var prop in json) {
              alert(json[prop]);
                          // or myArray.push(json[prop]) or whatever you want
         }
     }
 }
var a=[
{姓名:“汤姆”,文字:“美味”},
{姓名:“汤姆”,文字:“美味”},
{姓名:“汤姆”,文字:“美味”},
{姓名:“汤姆”,文字:“美味”},
{姓名:“汤姆”,文字:“美味”}
];
函数iter(){
对于(变量i=0;i
另一种解决方案:

var jsonArray = [
  { name: "Alice", text: "a" },
  { name: "Bob",   text: "b" },
  { name: "Carol", text: "c" },
  { name: "Dave",  text: "d" }
];

jsonArray.forEach(function(json){
  for(var key in json){
    var log = "Key: {0} - Value: {1}";
    log = log.replace("{0}", key); // key
    log = log.replace("{1}", json[key]); // value
    console.log(log);
  }
});
如果您想针对较新的浏览器,可以使用
对象。键

var jsonArray = [
  { name: "Alice", text: "a" },
  { name: "Bob",   text: "b" },
  { name: "Carol", text: "c" },
  { name: "Dave",  text: "d" }
];

jsonArray.forEach(function(json){
  Object.keys(json).forEach(function(key){
    var log = "Key: {0} - Value: {1}";
    log = log.replace("{0}", key); // key
    log = log.replace("{1}", json[key]); // value
    console.log(log);
  });
});

补充一句,json没有什么特别之处。它只是一个javascript对象初始化图。。在您的示例中,您有一个数组(方括号),其中包含对象(花括号语法)。。您应该检查javascript中的对象和数组文本,以揭示“魔力”
var jsonArray = [
  { name: "Alice", text: "a" },
  { name: "Bob",   text: "b" },
  { name: "Carol", text: "c" },
  { name: "Dave",  text: "d" }
];

jsonArray.forEach(function(json){
  Object.keys(json).forEach(function(key){
    var log = "Key: {0} - Value: {1}";
    log = log.replace("{0}", key); // key
    log = log.replace("{1}", json[key]); // value
    console.log(log);
  });
});