首页 > 解决方案 > 编码新手,我错过了什么?

问题描述

在 JS 上工作,我错过了什么?谢谢

修改下面的函数,只问候名字中字母为偶数的人

function helloYou(name)
 numbers.filter (n => n % 2 =i= 1);{

}

/* Do not modify code below this line */

console.log(helloYou('Bob'), `<-- should return undefined`)
console.log(helloYou('Anna'), `<-- should return "Hello, Anna!"`)

标签: javascript

解决方案


要访问字符串中的字母数,可以使用属性.length

然后检查这个数字是否是一个模数 2 应该返回 0,这就是我们需要检查的。这个条件在一个if语句中。

最后,如果满足此条件,则返回Hello与 连接name

否则什么都不返回,所以它是undefined(不需要显式地写return undefined)。

function helloYou(name) {
  if (name.length % 2 === 0) {
    return "Hello, " + name;
  }
}

/* Do not modify code below this line */

console.log(helloYou('Bob'), `<-- should return undefined`)
console.log(helloYou('Anna'), `<-- should return "Hello, Anna!"`)


推荐阅读