【发布时间】:2022-02-05 22:05:17
【问题描述】:
我的 JavaScript 老师给了我一个掌握函数的任务。我试图解决要求我像第二个代码一样输出的任务:
function showDetails(name = "unknown", age = "unknown", booleanez = "unknown") {
let name22ez,num22ez,bool22ez;
typeof booleanez === 'boolean'
? (bool22ez = booleanez)
: typeof booleanez === "number"
? (bool22ez = age)
: (bool22ez = name);
typeof name === "string"
? (name22ez = name)
: typeof name === "number"
? (name22ez = age)
: (name22ez = booleanez);
typeof age === "number"
? (num22ez = age)
: typeof age === "string"
? (num22ez = name)
: (num22ez = booleanez);
return `Hello ${name22ez}, Your Age Is ${num22ez}, You ${
bool22ez === true ? bool22ez =`Are` : bool22ez = `Are Not`
} Available For Hire`;
}
document.write(showDetails("Osama", 38, true));
document.write(`<hr>`);
document.write(showDetails(38, "Osama", true));
document.write(`<hr>`);
document.write(showDetails(true, 38, "Osama"));
document.write(`<hr>`);
document.write(showDetails(false, "Osama", 38));
输出是:
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello 38, Your Age Is false, You Are Available For Hire
我尝试了很多次,大概 4 个小时,来修复它,但我没有这样做,我从另一个学生那里得到了答案,他的答案是这样的:
function checkStatus(a, b, c) {
let str, num, bool;
typeof a === "string"
? (str = a)
: typeof b === "string"
? (str = b)
: (str = c);
typeof a === "number"
? (num = a)
: typeof b === "number"
? (num = b)
: (num = c);
typeof a === "boolean"
? (bool = a)
: typeof b === "boolean"
? (bool = b)
: (bool = c);
return `Hello ${str}, Your Age Is ${num}, You ${
bool ? "Are" : "Are Not"
} Available For Hire`;
}
document.write(checkStatus("Osama", 38, true));
document.write(checkStatus(38, "Osama", true));
document.write(checkStatus(true, 38, "Osama"));
document.write(checkStatus(false, "Osama", 38));
输出正确:
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello Osama, Your Age Is 38, You Are Available For Hire
Hello Osama, Your Age Is 38, You Are Not Available For Hire
我的代码和我同事的代码有什么区别?
【问题讨论】:
-
为什么所有不必要的类型检查?只需将一个对象传递给具有
name、age和forHire属性的函数并停止疯狂。 -
你的逻辑完全没有意义。您正在检查
name的类型,然后使用age作为分配给变量的值。 -
@J.Titus 这是一个任务,他应该复制原始函数以不同顺序处理参数的方式。他无法更改函数签名。
-
@Barmar 我明白,但这完全是愚蠢的。没有人会写出这样的代码。
-
不要使用嵌套的三元组,它们很混乱。也许如果你使用
if语句,你会做对的。
标签: javascript html typeof template-strings