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


Collect.js whenEmpty()用法及代碼示例

Collect.js是用於處理數組和對象的流利且便捷的包裝器。這個whenEmpty()函數當集合為空時執行回調函數。

安裝:使用以下命令安裝Collect.js模塊:

npm install --save collect.js

用法:

collection.whenEmpty(callback)

參數:此函數僅接受一個參數,即,如果集合為空,則執行該回調函數。

返回值:此函數返回新的集合對象。



範例1:Filename-index.js

Javascript

// Requiring module 
const collect = require('collect.js') 
  
// User defined collection 
var myCollection = [] 
  
// Creating collection object 
const collection = collect(myCollection); 
  
// Callback exection since collection object is empty 
collection.whenEmpty(item => item.push('Greetings')); 
  
// Printing collection 
console.log(collection.all());

使用以下命令運行index.js文件:

node index.js

輸出:

[ 'Greetings' ]

示例2:Filename-index.js

Javascript

// Requiring module 
const collect = require('collect.js') 
  
// User defined collection 
var myCollection = ['One', 'Two', 'Three'] 
  
// Creating collection object 
const collection = collect(myCollection); 
  
// No callback execution since collection is not empty 
collection.whenEmpty((item) => { 
  item.push('Four') 
  item.push('Five') 
  item.push('Six') 
}); 
  
// Printing collection 
console.log(collection.all());

使用以下命令運行index.js文件:

node index.js

輸出:

[ 'One', 'Two', 'Three']

參考:https://collect.js.org/api/whenEmpty.html

相關用法


注:本文由純淨天空篩選整理自gouravhammad大神的英文原創作品 Collect.js whenEmpty() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。