JavaScript virkne charCodeAt ()

Metode JavaScript virknes charCodeAt () atgriež veselu skaitli no 0 līdz 65535, kas norāda UTF-16 koda vienību dotajā indeksā.

Metodes sintakse charCodeAt()ir šāda:

 str.charCodeAt(index)

Šeit str ir virkne.

charCodeAt () parametri

charCodeAt()Metode ņem in:

  • indekss - vesels skaitlis starp 0 un str . garums - 1 . Ja indeksu nevar pārveidot par veselu skaitli vai tas nav norādīts, tiek izmantota noklusējuma vērtība 0 .

Atgriešanās vērtība no charCodeAt ()

  • Atgriež skaitli, kas apzīmē rakstā norādītā indeksa UTF-16 koda vienības vērtību.

Piezīmes :

  • charCodeAt()atgriežas, NaNja indekss ir negatīvs vai ir ārpus diapazona.
  • Ja Unicode punktu nevar attēlot vienā UTF-16 koda vienībā (vērtības pārsniedz 0xFFFF ), tas atgriež koda punktam pāra pirmo daļu. Visai koda punkta vērtībai izmantojiet codePointAt().

Piemērs: Izmantojot metodi charCodeAt ()

 let sentence = "Happy Birthday to you!"; let unicode1 = sentence.charCodeAt(2); console.log(`Unicode of '$(sentence.charAt(2))': $(unicode1)`); // 112 let unicode2 = sentence.charCodeAt(sentence.length - 1); console.log( `Unicode of '$(sentence.charAt(sentence.length - 1))': $(unicode2)` ); // 33 // index is 0 for non-numeric let unicode3 = sentence.charCodeAt("string"); console.log(`Unicode of '$(sentence.charAt(0))': $(unicode3)`); // 'p' // returns NaN for negative or out of range indices let unicode4 = sentence.charCodeAt(-2); console.log(`Unicode of '$(sentence.charAt(-2))': $(unicode4)`); // NaN

Rezultāts

 Unicode 'p': 112 Unicode of '!': 33 Unicode of H: 72 Unicode of '': NaN

Ieteicams lasīt: JavaScript virkne fromCharCode ()

Interesanti raksti...