仅过滤 JavaScript 中的空值
我们要求编写一个 JavaScript 函数,它接受一个包含一些 false 值的数组。该函数应在原地删除数组中所有空值(如果存在)。
例如:如果输入数组为 −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null];
则输出应为 −
const output = [12, 5, undefined, 0, false, 67, undefined, false];
示例
代码如下 −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined,
false, null];
const removeNullValues = arr => {
for(let i = 0; i < arr.length; ){
// null's datatype is object and it is a false value
// so only falsy object that exists in JavaScript is null
if(typeof arr[i] === 'object' && !arr[i]){
arr.splice(i, 1);
}else{
i++;
continue;
};
};
};
removeNullValues(arr);
console.log(arr);输出
控制台中的输出 −
[ 12, 5, undefined, 0, false, 67, undefined, false ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
Javascript
PHP