
- Node.js 教程
- Node.js - 首頁
- Node.js - 簡介
- Node.js - 環境搭建
- Node.js - 第一個應用程式
- Node.js - REPL 終端
- Node.js - 命令列選項
- Node.js - 包管理器 (NPM)
- Node.js - 回撥函式概念
- Node.js - 上傳檔案
- Node.js - 傳送電子郵件
- Node.js - 事件
- Node.js - 事件迴圈
- Node.js - 事件發射器
- Node.js - 偵錯程式
- Node.js - 全域性物件
- Node.js - 控制檯
- Node.js - 程序
- Node.js - 應用程式擴充套件
- Node.js - 打包
- Node.js - Express 框架
- Node.js - RESTful API
- Node.js - 緩衝區
- Node.js - 流
- Node.js - 檔案系統
- Node.js MySQL
- Node.js - MySQL 入門
- Node.js - MySQL 建立資料庫
- Node.js - MySQL 建立表
- Node.js - MySQL 插入資料
- Node.js - MySQL 從表中選擇資料
- Node.js - MySQL Where 條件
- Node.js - MySQL Order By 排序
- Node.js - MySQL 刪除資料
- Node.js - MySQL 更新資料
- Node.js - MySQL 聯接
- Node.js MongoDB
- Node.js - MongoDB 入門
- Node.js - MongoDB 建立資料庫
- Node.js - MongoDB 建立集合
- Node.js - MongoDB 插入資料
- Node.js - MongoDB 查詢資料
- Node.js - MongoDB 查詢
- Node.js - MongoDB 排序
- Node.js - MongoDB 刪除資料
- Node.js - MongoDB 更新資料
- Node.js - MongoDB 限制結果
- Node.js - MongoDB 聯接
- Node.js 模組
- Node.js - 模組
- Node.js - 內建模組
- Node.js - 實用程式模組
- Node.js - Web 模組
- Node.js 有用資源
- Node.js - 快速指南
- Node.js - 有用資源
- Node.js - 討論
Node.js - Buffer.fill() 方法
NodeJS buffer.fill() 方法用於使用給定值填充緩衝區。如果未指定緩衝區內的範圍,則將填充整個緩衝區。
語法
以下是 NodeJS fill() 方法的語法:
buf.fill(value[, offset[, end]][, encoding])
引數
buffer.fill() 方法接受四個引數。第一個引數 value 是必需的,其餘引數是可選的。
value - 這是必需的引數。它是您希望緩衝區填充的值。
offset - 這是一個可選欄位。offset 指示從哪裡開始填充值。預設值為 0。
end - 這是一個可選欄位。end 指示緩衝區填充在哪裡結束。預設值為緩衝區的長度。
encoding - 這是一個可選欄位。如果提供的值是字串,則需要考慮的編碼。預設值為 utf8。
返回值
它返回一個緩衝區物件,該物件將填充給定的值。
示例
在下面的示例中,我們使用 NodeJS Buffer.alloc() 建立了一個緩衝區,併為其分配了 10 個位元組。稍後使用 NodeJS buffer.fill() 將值 'ab' 填充到 10 個位元組的記憶體空間中。
const buffer = Buffer.alloc(10); buffer.fill('ab'); console.log("The final string from buffer is "+buffer.toString());
輸出
以下是上述程式的輸出:
The final string from buffer is ababababab
示例
在這個例子中,讓我們使用 offset 和 end 引數部分填充緩衝區。
使用 Buffer.alloc() 分配的空間為 10 個位元組。字串 'ab' 用於填充從 5 到 10 的緩衝區。
const buffer = Buffer.alloc(10); buffer.fill('ab', 5, 10); console.log(buffer); console.log("The final string from buffer is "+buffer.toString())
輸出
<Buffer 00 00 00 00 00 61 62 61 62 61> The final string from buffer is ababa
示例
在這個例子中,讓我們用整數填充緩衝區,如下所示:
const buffer = Buffer.alloc(10); console.log(buffer); buffer.fill(1); console.log(buffer);
輸出
在填充緩衝區之前,當您在控制檯中列印緩衝區時,您會看到全是零。稍後使用整數 1 填充緩衝區。輸出如下:
<Buffer 00 00 00 00 00 00 00 00 00 00> <Buffer 01 01 01 01 01 01 01 01 01 01>
示例
在這個例子中,我們將使用編碼。只有當值是字串時才能使用編碼。
const buffer = Buffer.alloc(10); console.log(buffer); buffer.fill("aazz","hex"); console.log(buffer);
輸出
上述示例中使用了十六進位制編碼。應用編碼後的輸出如上所示。
<Buffer 00 00 00 00 00 00 00 00 00 00> <Buffer aa aa aa aa aa aa aa aa aa aa>
示例
您還可以使用一個緩衝區作為值來填充另一個緩衝區。
const buffer1 = Buffer.allocUnsafe(8); buffer1.fill(Buffer.from('Hello')); console.log("The string is "+buffer1.toString());
輸出
在示例中,我們建立了一個名為 buffer1 的緩衝區,併為其分配了 8 個位元組。另一個緩衝區使用 Buffer.from() 方法和字串值“Hello”建立,並用作 buffer1 的值。
The string is HelloHel