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('');链接
鲍勃是个懒散的少年。在谈话中,他的反应非常有限。
鲍勃回答:“当然。”如果你问他一个问题。
他回答说:“哇,冷静点!”如果你对他大喊大叫。
他回答说:“冷静,我知道我在做什么!”如果你对他大喊大叫。
他说:“好吧,走那边!”如果你跟他说话却什么都没说。
他回答说:“随便你。”其他任何东西。
发布于 2018-05-16 08:25:14
您可以通过使用字符串或空字符串并与逻辑组进行比较来修剪字符串。
通过在return子句中使用if语句,可以省略else,因为如果true,则函数将以return结束。对于下一个检查,没有if就足够了。这种方法称为https://en.wikipedia.org/wiki/Structured_programming#Early_exit。
更多阅读:我应该尽早从函数返回,还是使用if语句?
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?'));
发布于 2018-05-16 08:14:28
它们是代码中的两个错误。
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'));
https://stackoverflow.com/questions/50365525
复制相似问题