【问题标题】:why( str === undefined) did not return anything为什么(str === undefined)没有返回任何东西
【发布时间】:2018-05-16 08:09:05
【问题描述】:
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('');

link

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

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

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

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

他说'好吧。就这样吧!如果你对他说话,实际上什么也没说。

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

【问题讨论】:

  • 代码应该做什么?
  • 1.) 删除 for 循环,你不需要它 2.) 我认为如果你比较 "" 而不是 " " 像:str === "" 和 @ 它应该可以正常工作987654326@ 因为你打电话给hey('') 而不是hey(' ')。为避免这种情况,您可以按照@Erazihel 的建议使用 .trim()

标签: javascript string if-statement


【解决方案1】:

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

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

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'));

【讨论】:

    【解决方案2】:

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

    通过在if 子句中使用return 语句,您可以省略else,因为如果true,函数将以return 终止。对于下一次检查,没有elseif 就足够了。这个方法叫做early exit

    更多阅读:Should I return from a function early or use an if statement?

    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?'));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多