繁体   English   中英

Javascript/jQuery:从数组中删除所有非数字值

[英]Javascript/jQuery: remove all non-numeric values from array

对于数组: ["5","something","","83","text",""]

如何从数组中删除所有非数字和空值? 期望的输出: ["5","83"]

使用array.filter()和一个检查值是否为数字的回调函数:

var arr2 = arr.filter(function(el) {
    return el.length && el==+el;
//  more comprehensive: return !isNaN(parseFloat(el)) && isFinite(el);
});

array.filter为IE8等旧版浏览器提供了array.filter

我需要这样做,并根据上面的答案跟随一个兔子踪迹,我发现这个功能现在已经以$.isNumeric()的形式内置到jQuery本身:

    $('#button').click(function(){
      // create an array out of the input, and optional second array.
      var testArray = $('input[name=numbers]').val().split(",");
      var rejectArray = [];

      // push non numeric numbers into a reject array (optional)
      testArray.forEach(function(val){
        if (!$.isNumeric(val)) rejectArray.push(val)
      });

      // Number() is a native function that takes strings and 
      // converts them into numeric values, or NaN if it fails.
      testArray = testArray.map(Number);

      /*focus on this line:*/
      testArray1 = testArray.filter(function(val){
        // following line will return false if it sees NaN.
        return $.isNumeric(val)
      });
    });

所以,你基本上是.filter() ,你给的函数.filter()$.isNumeric() ,它根据该项是否是数字给出一个真/假值。 有很好的资源可以通过谷歌轻松找到如何使用这些资源。 我的代码实际上将拒绝代码推送到另一个数组中,以通知用户他们上面提供了错误的输入,因此您有两个功能方向的示例。

这是一个ES6版本,虽然类似于 @Blazemonger 解决方案,但它更简化了一点:

 let arr = ["5","something","","83","text",""]; const onlyNumbers = arr.filter(v => +v); console.log(onlyNumbers);

在这里,我依赖于将字符串转换为数字的一元加操作数。 尽管有时它可能会导致一些意外行为(例如true未被过滤),但它与您的数组一起工作得很好,因为它只包含字符串。

暂无
暂无

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

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