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


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

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

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

npm install --save collect.js

用法:

collection.whenNotEmpty(callback)

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

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



範例1:Filename-index.js

Javascript

// Requiring module 
const collect = require('collect.js') 
  
// User defined collection 
var myCollection = [ 
    'Good Morning',  
    'Good Evening',  
    'Good Afternoon'
] 
  
// Creating collection object 
const collection = collect(myCollection); 
  
// Function call for single insertion 
collection.whenNotEmpty(item => item.push('Good Night')); 
  
// Printing collection 
console.log(collection.all());

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

node index.js

輸出:

[ 'Good Morning', 'Good Evening', 'Good Afternoon', 'Good Night' ]

示例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); 
  
// Function call for multiple insertion 
collection.whenNotEmpty((item) => { 
  item.push('Four') 
  item.push('Five') 
  item.push('Six') 
}); 
  
// Printing collection 
console.log(collection.all());

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

node index.js

輸出:

[ 'One', 'Two', 'Three', 'Four', 'Five', 'Six' ]

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

相關用法


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