當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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