📜  Collect.js whenEmpty()函数

📅  最后修改于: 2022-05-13 01:56:25.677000             🧑  作者: Mango

Collect.js whenEmpty()函数

Collect.js是用于处理数组和对象的流畅且方便的包装器。 whenEmpty ()函数在集合为空时执行回调函数。

安装:使用以下命令安装Collect.js模块:

npm install --save collect.js

句法:

collection.whenEmpty(callback)

参数:该函数只接受一个参数,即集合为空时执行的回调函数。

返回值:此函数返回新的集合对象。

示例 1:文件名-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());


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

输出:

[ 'Greetings' ]

示例 2:文件名-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