一个函数,它给出一个包含定义人名和年龄的对象的数组

时间:2018-05-20 04:25:59

标签: javascript

返回:一个字符串,格式为由逗号分隔的名称和年龄组列表,但最后两个名称除外,这两个名称应用&符号分隔。

年龄组被分解为:

  • 16岁以下的人被视为“孩子”
  • 年龄在16岁至59岁之间(包括在内),他们被视为“成年人”
  • 对于任何更高的东西,他们被认为是'高级'

例如:

listPeople([{
    name: 'Bart',
    age: 10
  },
  {
    name: 'Lisa',
    age: 20
  },
  {
    name: 'Maggie',
    age: 62
  }
]);

返回:

Bart the the kid,Lisa the adult& Maggie the senior

function listPeople(people) {
  var str = "";
  for(var i = 0; i < people.length; i++) {
    str += people[i].name;
    str += people[i].age;
    if(people[i].age <= 10 || people[i].age >= 20) {
      return people[i].name + "the kid " + people[i].age + "the adult " + "& " + people[i].age + "the senior";
    }
  }
}

3 个答案:

答案 0 :(得分:0)

您当前的代码并未对所提供的条件进行测试。您需要将数组中的最后一个人与其他人分开。迭代第一个人并加入逗号,然后为最后一个人执行相同的过程,但加入&而不是逗号。

因为您需要对每个人执行相同的转换,请尝试定义一个函数以将此人转换为格式正确的字符串,然后通过该函数发送每个人并根据需要加入/连接:

&#13;
&#13;
function personToString(person) {
  if (person.age < 16) return person.name + ' the kid';
  if (person.age > 59) return person.name + ' the senior';
  return person.name + ' the adult';
}

function listPeople(people) {
  const allButLastPeople = people.slice(0, people.length - 1);
  const lastPerson = people[people.length - 1];

  const firstString = allButLastPeople.map(personToString).join(', ');
  const lastString = personToString(lastPerson);
  console.log(firstString + ' & ' + lastString);
}

listPeople([{name:'Bart',age:10},{name:'Lisa',age:20},{name:'Maggie',age:62}]);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个(我在代码中添加了评论):

&#13;
&#13;
var l = listPeople([{
    name: 'Bart',
    age: 10
  },
  {
    name: 'Lisa',
    age: 20
  },
  {
    name: 'Maggie',
    age: 62
  }
]);

console.log(l);

function listPeople(people) {
  var str = "";
  for (var i = 0; i < people.length; i++) {
    //Add the person's name
    str += people[i].name;

    //Add the age designation
    if (people[i].age < 16)
      str += " the kid";
    else if (people[i].age < 60)
      str += " the adult";
    else
      str += " the senior";

    //Add the separator
    if (i < people.length - 2)
      str += ", ";
    else if (i == people.length - 2)
      str += " & ";
  }
  return str;
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

    function getLabel(age) {
      return age < 16
        ? ' the kid'
        : (age < 60 ? ' the adult' : ' the senior')
    }

    function listPeople(arr) {
      const formattedString = arr.reduce((acc, person, index) => {
        acc = acc.concat(person.name).concat(getLabel(person.age));
        acc = index !== arr.length - 1
          ? (index >= arr.length-2  ? acc.concat(' & ') : acc.concat(', '))
          : acc;
        return acc;
      }, '');
      return formattedString;
    }

    listPeople([{
        name: 'Bart',
        age: 10
      },
      {
        name: 'Lisa',
        age: 20
      },
      {
        name: 'Maggie',
        age: 62
      }
    ]);