getHeadline,返回一个报纸标题,我们'根据地点和在场的超级英雄,我会知道的



给定两个参数,一个超级英雄和一个城市,编写一个名为headline的函数,当(且仅当(我们的城市被拯救时,它会返回一个报纸标题——我们会根据位置和超级英雄在场来知道。

在这个DC/漫威漫画世界里,我们有这样的人:

Three superheros: Superman, Batman, Spiderman,
Three aliases: Clark Kent, Bruce Wayne, and Peter Parker,
And three locations: Metropolis, Gotham City, and New York City.

我们也知道每个别名都对应一个特定的超级英雄,所以…

The alias Clark Kent belongs to Superman,
Bruce Wayne belongs to Batman,
and Peter Parker belongs to Spiderman.

我们知道每个超级英雄都位于不同的城市。。。

Superman oversees Metropolis.
Batman patrols Gotham City.
Spiderman keeps New York City safe.

要了解这座城市是否被拯救,请确定提供的超级英雄是否在他们各自的城市。如果是这样的话,返回一个标题,如下所示:

__________, living under the alias of __________, saved the city of __________!

如果正确的超级英雄不在正确的城市,那么城市就不会被保存,函数应该返回一个空字符串(''(。

function getHeadline(superhero, city) {
var alias = '';
if (superhero !== 'Superman' && city !== 'Metropolis') {
console.log('');
} else if (superhero !== 'Batman' && city !== 'Gotham City') {
console.log('2');
} else if (superhero !== 'Spiderman' && city !== 'New York City') {
console.log('3');
} else {
if (superhero === 'Superman' && city === 'Metropolis') {
alias = 'Clark Kent';
} else if (superhero === 'Batman' && city === 'Gotham City'){
alias = 'Bruce Wayne';
} else if (superhero === 'Spiderman' && city === 'New York City'){
alias = "Peter Parker";
} else{
return superhero +", living under the alias of "+ alias +" ,saved the city of "+ city + "!";
}
}
}

这里有些过于复杂了。我们不需要像你现在这样多的病例,所以我们可以把它去掉一点。我们基本上需要做的是:

  1. 匹配超级英雄和城市
  2. a。如果匹配:设置别名
    b。如果不匹配:返回空字符串
  3. 返回格式化字符串

function getHeadline(superhero, city) {
var alias = '';
if (superhero === 'Superman' && city === 'Metropolis') {
alias = 'Clark Kent';
} else if (superhero === 'Batman' && city === 'Gotham City'){
alias = 'Bruce Wayne';
} else if (superhero === 'Spiderman' && city === 'New York City'){
alias = 'Peter Parker';
} else {
return '';
}

return superhero + ', living under the alias of ' + alias + ', saved the city of ' + city + '!';
}
console.log("('Superman', 'Metropolis'):n", getHeadline('Superman', 'Metropolis'));
console.log("('Superman', 'New York'):n", getHeadline('Superman', 'New York'));

你也有单引号和双引号的混合——我已经换成了单引号。一致性是关键!

也有人可能会说,我们可以将第二个if合并到if/else中,尽管

最新更新