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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。