创建一个新数组,包含原数组中所有的非假值元素。例如false, null,0, "", undefined, 和 NaN 都是被认为是“假值”。
例子:
_.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
根据loash官网的chunk方法自己写一个同样功能的方法
//_.cpmpadct(array)
//过滤掉假值的新数组
// _.compact([0, 1, false, 2, '', 3]);
// => [1, 2, 3]
let = [1,false,3,null,2,0,"",undefined,5,NaN] //if判断都为for
// compact()方法创建了去除了所有假值的新数组
function compact(array){
let resultIndex = 0; //结果数组索引
let result = []; //结果数组
//先判断,如果参数array为空,返回空数组
if(array == null) { //如果参数为array为空,返回空数组
return result = [];
}
for(let value of array) {
if(value) {
// result.push(value);
result[resultIndex++] = value; //如果当前值为真,就存入结果数组
}
}
return result;
}
console.log(compact([NaN,0,1,false,2,'',3,undefined,null]))
// console.log(compact([]));
网友评论