| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/API/TextEncoder/encodeInto | [Back] [Original] |
Get to know MDN better
encodeInto(string, uint8Array)
stringuint8Array Uint8Array UTF-8
encoder.encodeInto() TypedArray.prototype.subarray()
const encoder = new TextEncoder();
function encodeIntoAtPosition(string, u8array, position) {
return encoder.encodeInto(
string,
position ? u8array.subarray(position | 0) : u8array,
);
}
const u8array = new Uint8Array(8);
encodeIntoAtPosition("hello", u8array, 2);
console.log(u8array.join()); // 0,0,104,101,108,108,111,0
JavaScript s UTF-8 s.length s.length * 3 WASM s.length * 3 s.length * 3 3 s.length * 2 s.length * 2 + 5
roundUpToBucketSize(s.length) s.length * 3 t roundUpToBucketSize(s.length) + t >= s.length * 3 s.length * 3 roundUpToBucketSize(s.length) read s.length written + (s.length - read) * 3 s read written
roundUpToBucketSize() Wasm 2 roundUpToBucketSize() 2 2 Wasm roundUpToBucketSize()
2 3 2 3 0 WASM Rust 0 C++ C++ std::string C
U+0000encodeInto() 0x00 encodeInto() C 0x00
Wasm C 0x00 JavaScript U+0000 Wasm
const encoder = new TextEncoder();
function encodeIntoWithSentinel(string, u8array, position) {
const stats = encoder.encodeInto(
string,
position ? u8array.subarray(position | 0) : u8array,
);
if (stats.written < u8array.length) u8array[stats.written] = 0; // append null if room
return stats;
}
<p class="source">This is a sample paragraph.</p>
<p class="result"></p>
const sourcePara = document.querySelector(".source");
const resultPara = document.querySelector(".result");
const string = sourcePara.textContent;
const textEncoder = new TextEncoder();
const utf8 = new Uint8Array(string.length);
const encodedResults = textEncoder.encodeInto(string, utf8);
resultPara.textContent +=
`Bytes read: ${encodedResults.read}` +
` | Bytes written: ${encodedResults.written}` +
` | Encoded result: ${utf8}`;
| Encoding # ref-for-dom-textencoder-encodeinto |
| Web Proxy Viewer | New URL | Original Page |