buf[index]
index
<integer>
索引运算符 [index]
可用于获取和设置 buf
中位置 index
处的八位字节。
这些值是指单个字节,因此合法值范围介于 0x00
和 0xFF
(十六进制)或 0
和 255
(十进制)之间。
该运算符继承自 Uint8Array
,因此其越界访问行为与 Uint8Array
相同。
换句话说,当 index
为负或大于等于 buf.length
时,buf[index]
返回 undefined
,如果 index
为负或 >= buf.length
,buf[index] = value
不修改缓冲区。
// 每次一个字节地将 ASCII 字符串复制到 `Buffer` 中。
// (这仅适用于 ASCII-only 字符串。通常,应该使用 `Buffer.from()` 来执行此转换。)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// 打印: Node.js
index
<integer>
The index operator [index]
can be used to get and set the octet at position
index
in buf
. The values refer to individual bytes, so the legal value
range is between 0x00
and 0xFF
(hex) or 0
and 255
(decimal).
This operator is inherited from Uint8Array
, so its behavior on out-of-bounds
access is the same as Uint8Array
. In other words, buf[index]
returns
undefined
when index
is negative or greater or equal to buf.length
, and
buf[index] = value
does not modify the buffer if index
is negative or
>= buf.length
.
// Copy an ASCII string into a `Buffer` one byte at a time.
// (This only works for ASCII-only strings. In general, one should use
// `Buffer.from()` to perform this conversion.)
const str = 'Node.js';
const buf = Buffer.allocUnsafe(str.length);
for (let i = 0; i < str.length; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('utf8'));
// Prints: Node.js