Lodash _.compact()函数
Lodash被证明在处理数组、字符串、对象等时非常有用。它使数学运算和函数范式更容易、更简洁。 _.compact()函数用于创建一个数组,其中删除了 JavaScript 中的所有错误值。
句法:
_.compact(array)
参数:此函数只接受一个参数,如上所述,如下所述:
- array:要压缩的数组。
注意:值 false、null、0、“”、undefined 和 NaN 是错误的。
返回值:该函数返回过滤值后的数组。
为了更好地理解函数,下面给出了几个例子。
示例 1:将 true 和 false 元素的列表传递给 _.compact()函数。
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [0, 1, false, 2, '', 3];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [0, false, '', undefined, NaN];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [false, 'HTML', NaN,
'CSS', 'undefined'];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [false, true, 'yes', 'no', "no2"];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
输出:
示例 2:将包含所有错误值的列表传递给 _.compact()函数。
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [0, false, '', undefined, NaN];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
输出:
示例 3:将包含“中的错误元素”的列表传递给 _.compact()函数。
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [false, 'HTML', NaN,
'CSS', 'undefined'];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
输出:
示例 4:将包含修改后的 false 值的列表传递给 _.reduce()函数。
javascript
// Requiring the lodash library
let lodash = require("lodash");
// Original array to be compacted
let array = [false, true, 'yes', 'no', "no2"];
let newArray = lodash.compact(array);
console.log("Before compact: " + array);
// Printing newArray
console.log("After compact: " + newArray);
输出: