对于一个数组: ["5","something","","83","text",""]
如何从数组中删除所有非数字和空值? 期望的输出结果为: ["5","83"]
对于一个数组: ["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);
});
< p > < code >array.filter 可以为像 IE8 这样的旧浏览器提供 polyfill 支持。
这是一个 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);
我需要做这件事情,根据上面的答案进行了一些探索后,发现这个功能现在已经内置到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值。有很好的资源可以通过谷歌轻松找到,介绍如何使用这些函数。我的代码实际上将拒绝的代码推送到另一个数组中,以通知用户他们在上面输入了错误的内容,因此你有了两个方向功能的示例。