JavaScript programma, lai pārbaudītu, vai objektā ir atslēga

Šajā piemērā jūs iemācīsities rakstīt JavaScript programmu, kas pārbauda, ​​vai objektā pastāv atslēga.

Lai saprastu šo piemēru, jums jāpārzina šādas JavaScript programmēšanas tēmas:

  • JavaScript objekti
  • JavaScript objekts hasOwnProperty ()

1. piemērs: Pārbaudiet, vai Operatorā objekta lietošanā ir atslēga

 // program to check if a key exists const person = ( id: 1, name: 'John', age: 23 ) // check if key exists const hasKey = 'name' in person; if(hasKey) ( console.log('The key exists.'); ) else ( console.log('The key does not exist.'); )

Rezultāts

 Atslēga pastāv.

Iepriekš minētajā programmā inoperators tiek izmantots, lai pārbaudītu, vai objektā pastāv atslēga. Par inOperators atgriež true, ja norādītā atslēga ir objektu, pretējā gadījumā tā atgriež false.

2. piemērs. Pārbaudiet, vai objektā ir atslēga, izmantojot hasOwnProperty ()

 // program to check if a key exists const person = ( id: 1, name: 'John', age: 23 ) //check if key exists const hasKey = person.hasOwnProperty('name'); if(hasKey) ( console.log('The key exists.'); ) else ( console.log('The key does not exist.'); )

Rezultāts

 Atslēga pastāv.

Iepriekš minētajā programmā hasOwnProperty()metodi izmanto, lai pārbaudītu, vai objektā pastāv atslēga. Par hasOwnProperty()metode atgriež true, ja norādītā atslēga ir objektu, pretējā gadījumā tā atgriež false.

Interesanti raksti...