遍历每个名​​称并检查名称是否以“A”开头

时间:2017-07-09 04:34:19

标签: javascript arrays

遍历每个名​​称并检查名称是否以“A”开头 如果它确实向输出数组添加了一条消息,说明没有{人名的礼物} 否则,在输出数组中添加一条消息,说{Person's name}喜欢他们的礼物!

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i =0; i<person.length; i++){
    if (person.startsWith ("Aimee")){
      output.push(No gift for Aimee.);
    }
    if (person.startsWith ("Ariana"){
       output.push(No gift for Ariana.);
    }
    else {
    output.push(person[i] loved their gift);
    }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily']
gift = christmasTree [person, 'gift'];
console.log(gift);
//Output should look like: 
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]  
 

*无法获得所需的输出。请告知我如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

您的代码存在一些问题,您应该在people.length内检查christmasTree(people)。这不是你如何调用函数,调用use christmasTree(person)。然后,如果你在迭代人,你需要实际检查数组中的每个元素,使用people[i]

var person;
var gift;
function christmasTree(people){
   var output = [];
for (var i=0; i<people.length; i++){
    if (people[i].toUpperCase().startsWith("A")){
      output.push("No gift for " + person[i]);
    }
    else {
      output.push(people[i] + " loved their gift");
    }
  }
    return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily'];
gift = christmasTree(person);
console.log(gift);
//Output should look like: 
// This should be output:
  //   [
  //     "Billy loved their gift!",
  //     "Joel loved their gift!",
 //     "No gift for Aimee",
 //     "No gift for Ariana",
 //     "Zaire loved their gift!",
 //     "Lily loved their gift!",
 //  ]  
 

答案 1 :(得分:0)

您发布的代码中存在相当多的错误,例如,应按如下方式访问数组对象: person [i] .startsWith(“A”)而不是 person.startsWith(“A”)

请查看以下代码段:

function christmasTree(people){
    var output = [];
    for (var i =0; i<person.length; i++){
        if (person[i].toLowerCase().startsWith("a")) {
            output.push('No gift for' + person[i]);
        }
        else {
            output.push(person[i] + ' loved their gift');
        }
    }
return output;
}
person = ['Aimee', 'Ariana', 'Billy', 'Joel', 'Zaire', 'Lily'];
gift = christmasTree(person);
console.log(gift);