buffer.subarray()方法是缓冲区模块的内置应用程序编程接口,用于裁剪数组的一部分,即从数组创建sub-array。
用法:
Buffer.subarray( starting_index, ending_index )
参数:此方法具有上述和以下所述的两个参数:
- starting_index:此参数指定一个整数值,该整数值表示要从其开始新缓冲区的缓冲区的起始地址。其默认值为0。
- ending_index:它指定一个整数值,该整数值表示要创建新缓冲区的缓冲区的结束地址。默认值为缓冲区的长度。
返回值:此方法返回裁剪后的数组。该缓冲区指向相同的内存,但具有开始和结束索引。如果参数中的ending_index大于缓冲区长度,则将缓冲区长度作为结束索引。
注意:如果修改了新缓冲区,则相同的缓冲区将指向原始内存,反映在原始缓冲区中。
以下示例说明了Node.js中buffer.subarray()方法的使用:
范例1:
// Node.js program to demonstrate the
// Buffer.subarray() method
// Allocating buffer
const buf = Buffer.from('GeeksforGeeks', 'ascii');
// Printing original buffer
console.log("Original buffer is:" + buf);
// Cropping buffer, here starting index
// is 5 and ending endex is 10
cropped_buf = buf.subarray(5, 10);
// Printing cropped buffer
console.log("Cropped buffer is:" + cropped_buf);
// Modifying cropped buffer
cropped_buf[0] = 70; // F
cropped_buf[1] = 79; // O
cropped_buf[2] = 82; // R
// Printing cropped buffer
console.log("Cropped buffer after modification is:" + cropped_buf);
// Printing original buffer
console.log("Original buffer after modification is:" + buf);
输出:
Original buffer is:GeeksforGeeks Cropped buffer is:forGe Cropped buffer after modification is:FORGe Original buffer after modification is:GeeksFORGeeks
范例2:
// Node.js program to demonstrate the
// Buffer.subarray() method
// Allocating buffer
const buf = Buffer.from('GeeksforGeeks', 'ascii');
// Printing original buffer
console.log("Original buffer is:" + buf);
// Cropping buffer, here starting index
// is -10 and ending endex is -1
cropped_buf = buf.subarray(-12, -1);
// Printing cropped buffer
console.log("Cropped buffer is:" + cropped_buf);
// Cropping buffer again, here starting
// index is -10 and ending endex is -5
cropped_buf = buf.subarray(-10, -5);
// Printing cropped buffer
console.log("Cropped buffer is:" + cropped_buf);
// Cropping buffer again with no parameter
cropped_buf = buf.subarray();
// Printing cropped buffer
console.log("Cropped buffer is:" + cropped_buf);
输出:
Original buffer is:GeeksforGeeks Cropped buffer is:eeksforGeek Cropped buffer is:ksfor Cropped buffer is:GeeksforGeeks
注意:上面的程序将通过使用node index.js
命令。
参考: https://nodejs.org/api/buffer.html#buffer_buf_subarray_start_end
相关用法
注:本文由纯净天空筛选整理自gekcho大神的英文原创作品 Node.js | Buffer.subarray() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。