JS如何回报居住在城市中的人口数量?

时间:2018-12-21 14:06:20

标签: javascript arrays javascript-objects city

我是编码的新手,已经被问到了这个问题,但是我似乎无法使我的代码正常工作。有人对您有任何建议吗?

这是我得到的问题:

此函数以格式接收人对象数组:

[{ name: 'Sandra', lives: { country: 'UK', city: 'Manchester' }, age: 32 }]

该函数应返回居住在瓦伦西亚市的人数

这是我编写的代码;

function countPeopleInValencia(people) {
let count = 0
for (let i = 0; i < people.length; i++) {
  if (people.city[i] === 'Valencia') {
    count ++ }
  else {return 0}
  }
  return count
}

这就是我的代码将要针对的;

describe("countPeopleInValencia", () => {
it("returns 0 when nobody is from Valencia", () => {
expect(
  countPeopleInValencia([
    {
      name: "Sandra",
      lives: { country: "UK", city: "Manchester" },
      age: 32
    },
    {
      name: "Sandrella",
      lives: { country: "Spain", city: "Bilbao" },
      age: 32.5
    }
  ])
).to.equal(0);
  });
  it("returns the length of the array when everyone is from Valencia",   () => {
  expect(
  countPeopleInValencia([
    {
      name: "Cassandra",
      lives: { country: "Spain", city: "Valencia" },
      age: 32.5
    },
    {
      name: "Cassandrella",
      lives: { country: "Spain", city: "Valencia" },
      age: 35.55
    }
  ])
).to.equal(2);
 });
it("returns the number of people who are actually from the fair city of Valencia", () => {
expect(
  countPeopleInValencia([
    {
      name: "Melissandra",
      lives: { country: "Spain", city: "Valencia" },
      age: 55.5
    },
    {
      name: "Melissandrella",
      lives: { country: "Spain", city: "Valencia" },
      age: 55.555
    },
    {
      name: "Keith",
      lives: { country: "UK", city: "Newport Pagnell" },
      age: 2
    }
  ])
).to.eql(2);
expect(
  countPeopleInValencia([
    {
      name: "Imeldarina",
      lives: { country: "Spain", city: "Valencia" },
      age: 15.2
    },
    {
      name: "Bob",
      lives: { country: "Wales", city: "Abertillery" },
      age: 555555555555.555
    },
    {
      name: "Terry",
      lives: { country: "England", city: "Newport Pagnell" },
      age: 0.00000002
    }
  ])
).to.equal(1);
});
});

2 个答案:

答案 0 :(得分:1)

将计数移到for循环之外,您应该更正

people.city[i]

people[i]['lives']['city']

您的功能:

function countPeopleInValencia(people) {
  let count = 0
  for (let i = 0; i < people.length; i++) {
    if (people[i]['lives']['city'] === 'Valencia') {
      count++;
    }
  }
  return count
} 

答案 1 :(得分:0)

在您当前的代码中,一旦找到不在您要计数的城市中的人,您就返回计数值

function countPeopleInValencia(people) {
    let count = 0
    for (let i = 0; i < people.length; i++) {
        if (people.city[i] === 'Valencia') {
             count ++ 
        }
    }
    return count
}