target
{Buffer|Uint8Array} 要与buf
对比的Buffer
或 [Uint8Array
]。targetStart
{integer}target
中开始对比的偏移量。默认值:0
。targetEnd
{integer}target
中结束对比的偏移量(不包含)。默认值:target.length
。sourceStart
{integer}buf
中开始对比的偏移量。默认值:0
。sourceEnd
{integer}buf
中结束对比的偏移量(不包含)。默认值: [buf.length
]。- 返回: {integer}
对比 buf
与 target
,并返回一个数值,表明 buf
在排序上是否排在 target
前面、或后面、或相同。
对比是基于各自 Buffer
实际的字节序列。
- 如果
target
与buf
相同,则返回0
。 - 如果
target
排在buf
前面,则返回1
。 - 如果
target
排在buf
后面,则返回-1
。
const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');
console.log(buf1.compare(buf1));
// 打印: 0
console.log(buf1.compare(buf2));
// 打印: -1
console.log(buf1.compare(buf3));
// 打印: -1
console.log(buf2.compare(buf1));
// 打印: 1
console.log(buf2.compare(buf3));
// 打印: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// 打印: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (相当于: [buf1, buf3, buf2])
targetStart
、targetEnd
、sourceStart
与 sourceEnd
可用于指定 target
与 buf
中对比的范围。
const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]);
const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]);
console.log(buf1.compare(buf2, 5, 9, 0, 4));
// 打印: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// 打印: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// 打印: 1
如果 targetStart < 0
、sourceStart < 0
、targetEnd > target.byteLength
或 sourceEnd > source.byteLength
,则抛出 [ERR_OUT_OF_RANGE
]。