当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Node.js Buffer buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])用法及代码示例


buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])

历史
版本变化
v8.0.0

target 参数现在可以是 Uint8Array

v5.11.0

现在支持用于指定偏移的附加参数。

v0.11.13

添加于:v0.11.13


参数

比较 buftarget 并返回一个数字,指示 buf 在排序顺序中是在 target 之前、之后还是与 target 相同。比较基于每个 Buffer 中的实际字节序列。

  • 如果 targetbuf 相同,则返回 0
  • 1如果返回target应该来 buf排序时。
  • -1如果返回target应该来 buf排序时。
import { Buffer } from 'node:buffer';

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');

console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)const { Buffer } = require('node:buffer');

const buf1 = Buffer.from('ABC');
const buf2 = Buffer.from('BCD');
const buf3 = Buffer.from('ABCD');

console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
console.log([buf1, buf2, buf3].sort(Buffer.compare));
// Prints: [ <Buffer 41 42 43>, <Buffer 41 42 43 44>, <Buffer 42 43 44> ]
// (This result is equal to: [buf1, buf3, buf2].)

可选的 targetStarttargetEndsourceStartsourceEnd 参数可用于分别将比较限制在 targetbuf 内的特定范围内。

import { Buffer } from 'node:buffer';

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));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1const { Buffer } = require('node:buffer');

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));
// Prints: 0
console.log(buf1.compare(buf2, 0, 6, 4));
// Prints: -1
console.log(buf1.compare(buf2, 5, 6, 5));
// Prints: 1

如果 targetStart < 0sourceStart < 0targetEnd > target.byteLengthsourceEnd > source.byteLength ,则抛出 ERR_OUT_OF_RANGE

相关用法


注:本文由纯净天空筛选整理自nodejs.org大神的英文原创作品 buf.compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。