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

138
Vistas
¿Este error de NaNNaNNaN es causado por concatenación o algo más?

Al crear una tabla HTML usando javascript, termina mostrando "NaNNaNNaN" al lado de la tabla

NaNNaNNaN forma el .innerHTML usando la etiqueta html dentro del script

múltiples objetos en el .innerHTML

Aquí está el código:

 // Constructor function for Person objects function Person(first, last, relation, gender, age, eye) { this.firstName = first; this.lastName = last; this.relation = relation; this.gender = gender; this.age = age; this.eyeColor = eye; } // Create 2 Person objects const myFather = new Person("John", "Doe", "father", "Male", 50, "Blue"); const myMother = new Person("Sally", "Rally","mother", "Female", 48, "Green"); // Add a name method to first object myMother.name = function() { return "<table border= '2' align='center'>"+ "<tr>"+ "<th>"+"First Name"+"</th>"+ "<th>"+"Last Name"+"</th>"+ "<th>"+"Age"+"</th>"+ "<th>"+"Relation"+"</th>"+ "<th>"+"Gender"+"</th>"+ "<th>"+"Eye Color"+"</th>"+ +"</tr>"+ "<tr>"+ "<td>"+this.firstName+"</td>"+ "<td>"+this.lastName+"</td>"+ "<td>"+this.age+"</td>"+ "<td>"+this.relation+"</td>"+ "<td>"+this.gender+"</td>"+ "<td>"+this.eyeColor+"</td>"+ +"</tr>"+ +"</table>" }; // Display full name document.getElementById("demo").innerHTML += myMother.name();
 <!DOCTYPE html> <html> <body> <h2>JavaScript Object Constructors</h2> <p id="demo"> </p> </body> </html>

aquí está la salida

about 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

Como dice mplungjan, tiene demasiados signos más, pero esto es lo que sucede y por qué:

Cuando tiene este fragmento, el resultado es </tr>NaN .

 console.log("</tr>"+ +"</table>" )

¿Por qué? Por coerción de tipo forzado. El signo más adicional fuerza la conversión numérica de una cadena, por lo que "</table>" se convierte en un número. Un número no válido en este caso (NaN = No es un número).

 1 + "1" > '11' 1 + +"1" > 2 1 + + "not a number" > NaN "a string" + + "not a number" > 'a stringNaN'

Entonces, ¿por qué la tabla todavía se representa? Debido a un modelo de representación DOM permisivo. Si faltan algunos nodos, el navegador aún intentará representar los nodos DOM resultantes, completando las etiquetas finales faltantes según sea necesario.

about 4 years ago · Santiago Trujillo Denunciar

0

Tiene errores tipográficos (demasiados ++). Pero realmente quieres algo como esto.

¿Por qué solo tener una función de fila de tabla para la madre?

 function Person(first, last, relation, gender, age, eye) { this.firstName = first; this.lastName = last; this.relation = relation; this.gender = gender; this.age = age; this.eyeColor = eye; this.name = () => ` <tr> <td>${this.firstName}</td> <td>${this.lastName}</td> <td>${this.age}</td> <td>${this.relation}</td> <td>${this.gender}</td> <td>${this.eyeColor}</td> </tr>`; }; // Create 2 Person objects const myFather = new Person("John", "Doe", "father", "Male", 50, "Blue"); const myMother = new Person("Sally", "Rally", "mother", "Female", 48, "Green"); // Display full name document.getElementById("demo").innerHTML += myMother.name(); document.getElementById("demo").innerHTML += myFather.name();
 thead
 <table border='2' align='center'> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> <th>Relation</th> <th>Gender</th> <th>Eye Color</th> </tr> </thead> <tbody id="demo"></tbody> </table>

about 4 years ago · Santiago Trujillo Denunciar

0

permítame agregar... ¿por qué no usar la interpolación con literales de plantilla en sus variables, la utilización de marcas de retroceso...

 `<td> ${this.firstName} </td> <td> ${this.lastName} </td>`

te ahorrará mucho estrés y podrás deshacerte de los signos de concatenación +.

about 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