CKTIS / JavaScript
TextEncoder.encode in TypedArray.byteLength: štetje bajtov UTF-8
Kodirajte besedilo v UTF-8 in izmerite število dobljenih bajtov. Ločite ga od števila kodnih enot UTF-16, števila elementov tipizirane tabele in velikosti celotnega medpomnilnika.
Različica: ECMAScript 2024 and the current web platform; runtime support varies
Sintaksa
const encoder = new TextEncoder();
const bytes = encoder.encode(text);
const byteCount = bytes.byteLength;
// With no argument, encoder.encode() returns an empty Uint8Array.
// For any typed-array instance: view.byteLengthnew TextEncoder().encode(text) pokliče metodo primerka, ki niz kodira izključno v UTF-8 in vrne nov Uint8Array. Brez argumenta vrne prazen Uint8Array. Vsako neparno nadomestno kodno enoto zamenja z znakom U+FFFD, namesto da bi sprožila napako.
view.byteLength je lastnost samo za branje, ne metoda. Poda število bajtov pogleda; view.length šteje elemente, view.buffer.byteLength pa bajte v celotnem medpomnilniku. Če je pogled znotraj meja medpomnilnika, je view.byteLength enak view.length * view.BYTES_PER_ELEMENT. V Uint8Array vsak element zasede en bajt. text.length šteje kodne enote UTF-16, ne bajtov UTF-8. Za preverjanje omejitve v bajtih UTF-8 uporabite bytes.byteLength.
ECMAScript 2024 določa to lastnost tipiziranih tabel. TextEncoder je API spletne platforme, njegova razpoložljivost pa je odvisna od izvajalnega okolja. Pri medpomnilniku s spremenljivo velikostjo se lahko spremeni velikost pogleda, ki sledi velikosti medpomnilnika. Branje byteLength vrne 0, če je medpomnilnik odklopljen ali pogled sega čez njegove meje. Klic getterja na objektu, ki ni tipizirana tabela, sproži TypeError.
Primeri
{
const text = "Aé🙂";
const bytes = new TextEncoder().encode(text);
console.log(`text.length=${text.length}; bytes.length=${bytes.length}; bytes.byteLength=${bytes.byteLength}`);
console.log(bytes.join(","));
const view = new Uint16Array(new ArrayBuffer(12), 2, 3);
console.log(`view.length=${view.length}; view.byteLength=${view.byteLength}; view.buffer.byteLength=${view.buffer.byteLength}`);
}Rezultat
text.length=4; bytes.length=7; bytes.byteLength=7 65,195,169,240,159,153,130 view.length=3; view.byteLength=6; view.buffer.byteLength=12
`Aé🙂` obsega 4 kodne enote UTF-16 in 7 bajtov UTF-8. Pogled `Uint16Array` ima 3 elemente po 2 bajta, zato zajema 6 od 12 bajtov medpomnilnika.
Povezane lekcije
- JavaScript · Lekcija 17 · Napredna · Različica: 4