Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

335
Vistas
¿Cuál es la diferencia entre estas dos funciones que implican typeof

Mi profesor de JavaScript me dio una tarea para dominar las funciones. Traté de resolver la tarea que requiere que haga la salida como el segundo código:

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

La salida fue:

 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

Intenté muchas veces, como 4 horas, arreglarlo, pero no lo hice, tomé la respuesta de otro estudiante y su respuesta fue esta:

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

La salida fue correcta:

 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

¿Cuál es la diferencia entre el código mío y el de mi compañero?

over 4 years ago · Santiago Trujillo
4 Respuestas
Responde la pregunta

0

El código original comprueba el tipo de cada parámetro. El parámetro cuyo tipo es string se usa como nombre, el parámetro cuyo tipo es número se usa como edad y el parámetro cuyo tipo es booleano se usa como disponibilidad para contratar.

Tu lógica condicional es totalmente desconcertante para mí. La primera prueba en cada ternario es correcta: si booleanez es booleano, entonces debería usarse para bool22ez . Pero el resto no tiene sentido. Si booleanez es un número, ¿por qué significa que el parámetro de age debe asignarse a bool2ez ?

Debe usar la misma lógica que el original, probar cada parámetro para un tipo particular y luego usarlo como el valor para asignar a la variable que requiere ese tipo.

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

Y dado que está asignando la misma variable, debe usar el ternario solo en la parte de valor de la asignación en lugar de repetir la variable a la que asignar.

 bool22ez = typeof booleanez === 'boolean' ? booleanez : typeof age === "boolean" ? age : name;
over 4 years ago · Santiago Trujillo Denunciar

0

Para agregar a la respuesta de Barmar , este es el código correcto:

 function showDetails(name = "unknown", age = "unknown", booleanez = "unknown") { let name22ez,num22ez,bool22ez; typeof name === "string" ? (name22ez = name) : typeof age === "string" ? (name22ez = age) : (name22ez = booleanez); typeof age === "number" ? (num22ez = age) : typeof name === "number" ? (num22ez = name) : (num22ez = booleanez); typeof booleanez === 'boolean' ? (bool22ez = booleanez) : typeof name === "boolean" ? (bool22ez = name) : (bool22ez = age); return `Hello ${name22ez}, Your Age Is ${num22ez}, You ${ bool22ez === true ? bool22ez =`Are` : bool22ez = `Are Not` } Available For Hire`; }
over 4 years ago · Santiago Trujillo Denunciar

0

Lamento descarrilar la sección de comentarios de tu publicación. Mi punto es que una forma más sensata de escribir esta función sería algo así como:

 function showDetails(details) { // do some type checking up here for the existence of the values // because JavaScript is not a strongly typed language // ... // return the result if the details are provided return `Hello ${details.name}, Your Age Is ${details.age}, You ${details.forHire ? 'Are' : 'Are Not'} Available For Hire`; } console.log(showDetails({ name: 'Osama', age: 38, forHire: true })) console.log(showDetails({ name: 'Osama', age: 38, forHire: false }))

Sin embargo, específicamente para su tarea, escuche a @Barmar.

over 4 years ago · Santiago Trujillo Denunciar

0

Incluso si estoy muy de acuerdo con Barmar cuando dice que es completamente estúpido. Nadie en su sano juicio escribiría un código como este. , Me encantan esos desafíos.

Eche un vistazo a la solución que sugeriría si fuera usted:

 function showDetails(name = "unknown", age = "unknown", booleanez = "unknown") { // Accept specific types and one of each let acceptedTypes = ["string", "number", "boolean"]; let typeSet = Array.from(new Set([typeof name, typeof age, typeof booleanez])); if (typeSet.length != 3) { return "ERROR - I need 3 different types of argument."; } for (let i = 0; i < typeSet.length; i++) { if (acceptedTypes.indexOf(typeSet[i]) == -1) { return "ERROR - At least one argument is not accepted."; } } // Beyond this point, proceed! let args = [ { type: typeof name, value: name }, { type: typeof age, value: age }, { type: typeof booleanez, value: booleanez } ]; // Expecting in this order: "string", "number", "boolean" // which are in the reversed alphabetical order... // So use sort ba on the types ;) args.sort((a, b) => b.type.localeCompare(a.type)) return `Hello ${args[0].value}, Your Age Is ${args[1].value}, You Are ${args[2].value ? `` : `Not `}Available For Hire`; } console.log(showDetails("Osama", 38, true)); console.log(showDetails(38, "Osama", true)); console.log(showDetails(true, 38, "Osama")); console.log(showDetails(false, "Osama", 38)); console.log(showDetails(0, "Osama", 38)); console.log(showDetails(0, "Osama", { age: 38 })); console.log(showDetails());

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda