Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
La mejor manera de verificar un atributo de un objeto que podría no estar definido

Tengo un objeto (oUsed) que contiene campos "bloqueados" de una cuadrícula. Si un campo está bloqueado, es "verdadero". Si no está bloqueado, es indefinido.

Lo que puede suceder ahora es que una línea completa (valor de la coordenada x) no esté bloqueada. Entonces, el siguiente código fallará, ya que verifica el atributo de un objeto indefinido.

 let oUsed = { "x1":{ "y2": true; "y3": true; } "x3":{ "y2": true; } } let iY = 2; for (let iX=1;iX <= 3; iX++) { if (oUsed[`x${iX}`][`x${iY}`]) { break; } }

Hacerlo en dos pasos funciona, pero no es muy bonito.

 for (let iX=1;iX <= 3; iX++) { if (oUsed[`x${iX}`]) { if (oUsed[`x${iX}`][`x${iY}`]) { break; } } }

¿Cuál es la mejor práctica para este tipo de verificación?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Use Object.hasOwnProperty u Object.hasOwn

 if (oUsed.hasOwnProperty(`x${iX}`) && oUsed[`x${iX}`][`x${iY}`])

o

usar así

 if (oUsed[`x${iX}`] && oUsed[`x${iX}`][`x${iY}`]) {

o si su navegador de destino admite el encadenamiento opcional

 if (oUsed[`x${iX}`]?.[`x${iY}`])
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!