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

对于数组: ["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

我需要这样做,并根据上面的答案跟踪一个兔子踪迹,我发现这个function现在已经以$.isNumeric()的forms内置到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() ,它根据该项是否为数字给出一个真/假值。 有很好的资源可以通过谷歌轻松找到如何使用这些资源。 我的代码实际上将拒绝代码推送到另一个数组中以通知用户他们上面提供了错误的输入,因此您有两个function方向的示例。