【发布时间】:2016-09-15 20:02:39
【问题描述】:
在 javascript 中,我想删除未定义的值,但从数组中保留值 0 和 null。
[ 1, 2, 3, undefined, 0, null ]
怎样才能干净利落?
【问题讨论】:
标签: lodash
在 javascript 中,我想删除未定义的值,但从数组中保留值 0 和 null。
[ 1, 2, 3, undefined, 0, null ]
怎样才能干净利落?
【问题讨论】:
标签: lodash
你可以使用_.compact(array);
创建一个删除所有错误值的数组。值 false、null、0、""、undefined 和 NaN 为 false。
【讨论】:
false、null、0、""、undefined 和 NaN 正在被 _.compact 删除。
【讨论】:
不需要现代浏览器的库。 filter 是内置的。
var arr = [ 1, 2, 3, undefined, 0, null ];
var updated = arr.filter(function(val){ return val!==undefined; });
console.log(updated);
【讨论】:
ECMA-262 中添加的,这是规范的一个相当旧的版本,所以在实践中,这与其说是一种 polyfill,不如说是一种“标准实现”。跨度>
使用lodash,您可以做的很简单:
var filtered = _.reject(array, _.isUndefined);
如果您还想过滤 null 以及 undefined 在某些时候:
var filtered = _.reject(array, _.isNil);
【讨论】:
使用 lodash,以下内容仅从数组中删除未定义的值:
var array = [ 1, 2, 3, undefined, 0, null ];
_.filter(array, function(a){ return !_.isUndefined(a) }
--> [ 1, 2, 3, 0, null ]
或者,以下将删除未定义、0 和 null 值:
_.filter(array)
--> [1, 2, 3]
如果你想从数组中删除空值和未定义值,但保持值等于 0:
_.filter(array, function(a){ return _.isNumber(a) || _.isString(a) }
[ 1, 2, 3, 0 ]
【讨论】:
使用 ES6 Array#filter 方法
array.filter(item => item !== undefined)
【讨论】:
foo.filter(Boolean)!
Vanilla JS 解决方案:
通过使用===,您可以检查该值是否实际上是undefined 而不是falsy。
下面的两个 sn-ps 都会给你一个带有 [1, 2, 3, 0, null] 的数组。
两者都修改了原始数组。
// one liner - modifies the array in-place
[ 1, 2, 3, undefined, 0, null ].forEach( function(val, i, arr){
if(val===undefined){arr.splice(i,1)}; // remove from the array if actually undefined
});
// broken up for clarity - does the same as the above
var myarray = [ 1, 2, 3, undefined, 0, null ];
myarray.forEach( function(val, i, arr){
if(val===undefined){arr.splice(i,1)};// remove from the array if actually undefined
});
console.log(myarray );
【讨论】:
您可以使用 lodash 来执行此操作,
你可以使用_.omitBy(object, _.isUndefined); https://lodash.com/docs/4.17.15#omitBy
在 _.isUndefined 的地方,你甚至可以使用 _.isNumber、_.isNull 和很多函数。
转到lodash webside,在搜索中搜索“is”即可得到函数列表。
【讨论】:
普通 ES6:
array.filter(a => a !== undefined)
【讨论】:
你可以试试这个。
var array = [ 1, 2, 3, undefined, 0, null ];
var array2 = [];
for(var i=0; i<array.length; i++){
if(!(typeof array[i] == 'undefined')){
array2.push(array[i]);
}
}
console.log(array2);
【讨论】:
过滤给定数组中不等于未定义的元素。
const initialArray = [ 1, 2, 3, undefined, 0, null ];
const finalArray = initialArray.filter(element => element !== undefined);
【讨论】:
const finalArray = initialArray.filter(i => Boolean(i))
【讨论】: