buf.slice([start[, end]])
start<integer> 新的Buffer将从此处开始。默认值:0。end<integer> 新的Buffer将在此结束(不包括在内)。默认值:buf.length。- 返回:<Buffer>
稳定性: 0 - 弃用:请改用
buf.subarray。返回一个新的 Buffer,它引用与原始缓冲区相同的内存,但通过 start 和 end 索引进行了偏移和裁剪。
【Returns a new Buffer that references the same memory as the original, but
offset and cropped by the start and end indices.】
此方法与 Uint8Array.prototype.slice() 不兼容,Uint8Array.prototype.slice() 是 Buffer 的超类。若要复制切片,请使用 Uint8Array.prototype.slice()。
【This method is not compatible with the Uint8Array.prototype.slice(),
which is a superclass of Buffer. To copy the slice, use
Uint8Array.prototype.slice().】
import { Buffer } from 'node:buffer';
const buf = Buffer.from('buffer');
const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Prints: buffer
// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)const { Buffer } = require('node:buffer');
const buf = Buffer.from('buffer');
const copiedBuf = Uint8Array.prototype.slice.call(buf);
copiedBuf[0]++;
console.log(copiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Prints: buffer
// With buf.slice(), the original buffer is modified.
const notReallyCopiedBuf = buf.slice();
notReallyCopiedBuf[0]++;
console.log(notReallyCopiedBuf.toString());
// Prints: cuffer
console.log(buf.toString());
// Also prints: cuffer (!)