简体   繁体   English

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

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

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

How to remove all non-numeric and empty values from an array?如何从数组中删除所有非数字和空值? Desired output: ["5","83"]期望的输出: ["5","83"]

Use array.filter() and a callback function that checks if a value is numeric : 使用array.filter()和一个检查值是否为数字的回调函数:

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

array.filter has a polyfill for older browsers like IE8. array.filter为IE8等旧版浏览器提供了array.filter

I needed to do this, and following a bunny trail based on the answer above, I found out that this functionality has now been built in to jQuery itself in the form of $.isNumeric() : 我需要这样做,并根据上面的答案跟随一个兔子踪迹,我发现这个功能现在已经以$.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)
      });
    });

So, you essentially .filter() , and the function you give .filter() is $.isNumeric() , which gives a true/false value depending on whether that item is numeric or not. 所以,你基本上是.filter() ,你给的函数.filter()$.isNumeric() ,它根据该项是否是数字给出一个真/假值。 Good resources are available and easily found via google on how these are used. 有很好的资源可以通过谷歌轻松找到如何使用这些资源。 My code actually pushes the reject code out into another array to notify the user they gave bad input up above, so you have an example of both directions of functionality. 我的代码实际上将拒绝代码推送到另一个数组中,以通知用户他们上面提供了错误的输入,因此您有两个功能方向的示例。

Here is an ES6 version, although being similar to @Blazemonger solution, it's a bit more simplified:这是一个ES6版本,虽然类似于 @Blazemonger 解决方案,但它更简化了一点:

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

Here, I am relying on the unary plus operand which converts a string into a number.在这里,我依赖于将字符串转换为数字的一元加操作数。 Althought sometimes it might lead to some unexpected behaviour (for example true is not filtered), it works just fine with your array since it contains only strings.尽管有时它可能会导致一些意外行为(例如true未被过滤),但它与您的数组一起工作得很好,因为它只包含字符串。

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

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