迭代数组并将所选条目记录到控制台

时间:2017-01-27 15:10:45

标签: javascript arrays for-loop

我有一个名为customers的数组,每个客户都有一个名称,ID,帐号,地址和帐户信息:

var customers = [
    {
        "name": "John Doe",
        "id": 1205,
        "accountNumber": 187456,
        "address": {
            "houseNumber": 12,
            "streetName": "made up street",
            "postCode": "WE1 234",
            "area": "Birmingham"
        },
        "hasCurrentAccount": true,
        "hasLoan": false,
        "hasMortgage": true
    },
    {
        "name": "Jane Doe",
        "id": 1304,
        "accountNumber": 123456,
        "address": {
            "houseNumber": 420,
            "streetName": "The Street",
            "postCode": "DE3 456",
            "area": "Wolverhampton"
        },
        "hasCurrentAccount": false,
        "hasLoan": true,
        "hasMortgage": false
    }
];

现在,我试图遍历此数组,检索名称和ID并将其打印到控制台:

var info = customers;
for (var i in info)
{
   var id = info.id;
   var name = info.name;
   console.log('Here are your current customers' + id + ' ' + name);
}

但我得到了

Here are your current customers undefined undefined

我尝试了不同的方法,但我似乎无法让它发挥作用。 有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

这将解决您的问题。

for (a in customers){
console.log('Here are your current customers' + a + ' ' + customers[a].name);
}

答案 1 :(得分:0)

您可以使用Array.forEach函数迭代数组。 它在每个项目上运行一个函数,您可以在该项目中将值从项目记录到控制台。

示例:



var customers = [
    {
        "name": "John Doe",
        "id": 1205,
        "accountNumber": 187456,
        "address": {
            "houseNumber": 12,
            "streetName": "made up street",
            "postCode": "WE1 234",
            "area": "Birmingham"
        },
        "hasCurrentAccount": true,
        "hasLoan": false,
        "hasMortgage": true
    },
    {
        "name": "Jane Doe",
        "id": 1304,
        "accountNumber": 123456,
        "address": {
            "houseNumber": 420,
            "streetName": "The Street",
            "postCode": "DE3 456",
            "area": "Wolverhampton"
        },
        "hasCurrentAccount": false,
        "hasLoan": true,
        "hasMortgage": false
    }
];

customers.forEach(function(item) {
  console.log('Here are your current customers', item.id, item.name);
})