Clone and edit this document
Runkit
Runkit
home page
user forum
new notebook
clone notebook
download notebook
support & documentation
log in
sign up
new notebook
help & feedback
clone this notebook
download this notebook
Sign In
Sign Up
_.compact
node v6.17.1
version:
2.0.0
endpoint
share
tweet
const _ = require('lodash'); // compact function function compact(array){ let resIndex = 0; const result = []; if(array == null){ return result; } for(const value of array){ if(value){ result[resIndex++] = value; } } return result; }
let test = [0, 1, '', 2, false, 3, null, 4, undefined, 5, NaN, 6];
compact(test)
_.compact(test)
/* 使用while进行数组的循环 */ function compact_use_while(array) { // 判断array是否为空 if(array == null) { return []; } let result = []; let index = 0; let resIndex = 0; let value; const length = array.length; while(index < length) { value = array[index]; if(value) { result[resIndex++] = value; } index++; } return result; }
compact_use_while(test)
/* 使用数组的map方法 */ function compact_use_map(array) { // 判断array是否为空 if(array == null) { return []; } let result = []; array.map((value) => { if(value) { result.push(value); } }); return result; }
compact_use_map(test)
Loading…
no comments
sign in
to comment