首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么( str ===未定义)没有返回任何内容

为什么( str ===未定义)没有返回任何内容
EN

Stack Overflow用户
提问于 2018-05-16 08:09:05
回答 2查看 54关注 0票数 1
代码语言:javascript
复制
function hey(str) {
    for (let char of str){
        if (str.slice(-1) !== "?" && str === str.toUpperCase() && str !== " "){
            return 'Whoa, chill out!';
        }
        else if (str.slice(-1) === "?" && str === str.toUpperCase()){
            return "Calm down, I know what I'm doing!";
        }
        else if(str.slice(-1) === "?" && str !== str.toUpperCase()){
            return "Sure.";
        }
        else if (str === " " || str === undefined){
            return "Fine. Be that way!";
        }
        else {
          return 'Whatever.';
        }
    }
}

hey('');

链接

鲍勃是个懒散的少年。在谈话中,他的反应非常有限。

鲍勃回答:“当然。”如果你问他一个问题。

他回答说:“哇,冷静点!”如果你对他大喊大叫。

他回答说:“冷静,我知道我在做什么!”如果你对他大喊大叫。

他说:“好吧,走那边!”如果你跟他说话却什么都没说。

他回答说:“随便你。”其他任何东西。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-16 08:25:14

您可以通过使用字符串或空字符串并与逻辑组进行比较来修剪字符串。

通过在return子句中使用if语句,可以省略else,因为如果true,则函数将以return结束。对于下一个检查,没有if就足够了。这种方法称为https://en.wikipedia.org/wiki/Structured_programming#Early_exit

更多阅读:我应该尽早从函数返回,还是使用if语句?

代码语言:javascript
复制
function hey(str) {
    str = (str || '').trim();
    if (str === "") {
        return "Fine. Be that way!";
    }
    if (str.slice(-1) === "?") {
        return str === str.toUpperCase()
            ? "Calm down, I know what I'm doing!"
            : "Sure.";
    }
    return str === str.toUpperCase()
        ? 'Whoa, chill out!'
        : 'Whatever.';
}

console.log(hey(''));
console.log(hey('BOA!'));
console.log(hey('BOA?'));
console.log(hey('ok!'));
console.log(hey('ok?'));

票数 0
EN

Stack Overflow用户

发布于 2018-05-16 08:14:28

它们是代码中的两个错误。

  • for循环是不必要的。
  • 您必须使用trim函数来删除无用的空格,以便比较对Bob所说的是空字符串还是空字符串。

代码语言:javascript
复制
function hey(str) {
    const trimmedStr = (str || '').trim();
  
    if (trimmedStr === '') {
        return "Fine. Be that way!";
    }

    if (trimmedStr.slice(-1) === "?") {
      return trimmedStr === trimmedStr.toUpperCase()
        ? "Calm down, I know what I'm doing!"
        : "Sure.";
    }
     
    return trimmedStr === trimmedStr.toUpperCase()
      ? 'Whoa, chill out!'
      : 'Whatever.';
}

console.log(hey(' '));
console.log(hey('FOO?'));
console.log(hey('Foo?'));
console.log(hey('FOO'));
console.log(hey('Foo'));

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50365525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档