如何从数组,JavaScript中列出的字典中打印键和值

时间:2018-07-30 15:49:59

标签: javascript arrays dictionary printing

在使用double for循环和

从存储在数组中的字典中打印数据时,我遇到了困难
var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

function people() {
    for (let i = 0; i < residents.length; i++) {
        for (let j in residents[i]) {
            document.write(j + ": " + residents[j] + "<br>");
        }
    }
};

people();

我要检索的是:

name: undefined 
room: undefined
name: undefined
room: undefined

我可以打印密钥,但似乎无法获取为密钥定义的值! 我究竟做错了什么?

成功的标准是使用HTML打印。

6 个答案:

答案 0 :(得分:1)

您已将两个循环链接在一起,因此您的函数需要访问父索引,然后访问要引用的属性。

function people() {
    for (let i = 0; i < residents.length; i++) {
        for (let j in residents[i]) {
            document.write(j + ": " + residents[i][j] + "<br>");
        }
    }
};

答案 1 :(得分:1)

为什么不尝试使用forEach()

var residents = [{
  name: "Pyrus",
  room: "32"
}, {
  name: "Ash Ketchum",
  room: "22"
}];

function people(residents) {
  residents.forEach((element) => {
    for (var key in element) {
      if (element.hasOwnProperty(key)) {
        console.log(key + ':' + element[key]);
      }
    }
  });

};
people(residents);

答案 2 :(得分:1)

这是我认为的最简单方法(使用foreach()):

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

function people() {
    residents.forEach(function(resident) {
 document.write(resident.name + ": " + resident.room + "<br>");
});

}
people();

答案 3 :(得分:0)

您可以避免一些CustomDatatype循环,并使用forforEach使代码更易于阅读:

Object.entries

答案 4 :(得分:0)

由于您首先要迭代居民,因此您需要访问residents[i][j]

因此您的代码变为:

document.write(j + ": " + residents[i][j] + "<br>");

查看此working js fiddle

您也可以这样写:

function people(){
    residents.forEach(r => {
        for(let j in r){
          document.write(j + ": " + r[j] + "<br>");
      }
    })
}

希望这会有所帮助。

答案 5 :(得分:0)

使用常规的for循环将类似于以下代码。另外,我强烈建议您检查所有属性(j)是否都是自己的属性(带有hasOwnProperty),否则将在原型链中查找。如果将对象动态添加到数组中,可能会出现问题,否则您可以跳过此检查。

var residents = [{name:"Pyrus",room:"32"},{name: "Ash Ketchum",room:"22"}];

function people() {
  for (let i = 0; i < residents.length; i++) {
    for (let j in residents[i]) {
      if (residents[i].hasOwnProperty(j)) { // <-- check if it is an own property!
        document.write(j + ": " + residents[i][j] + "<br>");
        //first access the object in residents[i], for example {name: "Pyrus",room: "32"}, then to its properties-values with residents[i][j]
      }
    }
  }
};

people();