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

6

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

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

3个回答

7

如果被过滤的数组包含'null',则您的函数会抛出错误。示例输入:let arr = [ 0, 'a', () => console.log('?'), false, { a: '5' }, 7, 8, 9, '100', NaN, null, undefined, -Infinity, Infinity, ]; - emre-ozgun

5

这是一个 ES6 版本,用于测试数组中的值是否与 regexp 匹配

let arr = ["83", "helloworld", "0", "", false, 2131, 3.3, "3.3", 0];
const onlyNumbers = arr.filter(value => /^-?\d+\.?\d*$/.test(value));
console.log(onlyNumbers);


1

我需要做这件事情,根据上面的答案进行了一些探索后,发现这个功能现在已经内置到jQuery中,以$.isNumeric()的形式存在:

    $('#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(),并给出了一个函数$.isNumeric(),它根据该项是否为数字给出true/false值。有很好的资源可以通过谷歌轻松找到,介绍如何使用这些函数。我的代码实际上将拒绝的代码推送到另一个数组中,以通知用户他们在上面输入了错误的内容,因此你有了两个方向功能的示例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接