gpt4 book ai didi

javascript - 这两个涉及typeof的函数有什么区别

转载 作者:行者123 更新时间:2023-12-05 03:29:43 24 4
gpt4 key购买 nike

我的 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

我的代码和我同事的代码有什么区别?

最佳答案

原始代码检查每个参数的类型。类型为string的参数用作姓名,类型为number的参数用作年龄,类型为boolean的参数用作可租用时间。

你的条件逻辑让我完全摸不着头脑。每个三元组中的第一个测试都是正确的——如果 booleanez 是 bool 值,那么它应该用于 bool22ez。但其余的没有意义。如果 booleanez 是一个数字,为​​什么这意味着 age 参数应该分配给 bool2ez

您需要使用与原始逻辑相同的逻辑,测试特定类型的每个参数,然后将其用作分配给需要该类型的变量的值。

  typeof booleanez === 'boolean'
? (bool22ez = booleanez)
: typeof age === "boolean"
? (bool22ez = age)
: (bool22ez = name);

并且由于您正在分配相同的变量,因此您应该只在分配的值部分使用三元组而不是重复要分配给的变量。

bool22ez = 
typeof booleanez === 'boolean'
? booleanez
: typeof age === "boolean"
? age
: name;

关于javascript - 这两个涉及typeof的函数有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70965125/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com