简体   繁体   English

从数组中删除虚假值会使我留空值。 如何改善我的代码?

[英]Removing falsy values from a array leaves me with null values. How to Improve my code?

I'm trying to remove the falsy values from an array. 我试图从数组中删除伪造的值。 I tried usign typeOf and Boolean, but that would leave me with null values inside my array. 我尝试使用usign typeOf和Boolean,但这会使我在数组内留空值。 How can I improve my code? 如何改善我的代码?

function bouncer(arr) {
    var myarr=[];
    for(var i=0;i<arr.length;i++)
    {
        if(typeof arr[i] === 'boolean' || arr[i]=== 0 || arr[i]==="")
        {
            delete arr[i];
        }

    }
    return arr;
}

bouncer([7, "ate", "", false, 9]);

The outout from this code: 此代码的结果:

([7, "ate", null, null, 9])

How can I improve this code ? 如何改善此代码? Why does typeOf ==='boolean' not delete 0 and null string "". 为什么typeOf ==='boolean'不会删除0和空字符串“”。

Update: The code should satisfy the below criteria. 更新:该代码应满足以下条件。

bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9].
bouncer(["a", "b", "c"]) should return ["a", "b", "c"].
bouncer([false, null, 0, NaN, undefined, ""]) should return [].

Thank you 谢谢

Could it be as simple as this? 这样简单吗?

 var arr = [7, "ate", "", false, 9, "a", "b", "c", false, null, 0, NaN, undefined, ""]; var result = arr.filter(a=>a); // [7, "ate", 9, "a", "b", "c"] console.log(document.body.innerHTML = result); 

var newArr = [];
arr.forEach(function(element) {
    if (element != false)
        newArr.push(element);
});
return newArr;

尝试是否(!arr [i]){arr.splice(i,1)}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM