对于数组:
["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 等旧版浏览器的 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);
我需要这样做,并根据上面的答案进行了跟踪,我发现这个功能现在已经以
$.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()
,它根据该项目是否是数字给出一个真/假值。通过谷歌可以轻松找到关于如何使用这些资源的优质资源。我的代码实际上将拒绝代码推送到另一个数组中,以通知用户他们在上面给出了错误的输入,因此您有一个功能两个方向的示例。
const arr = ["5","东西","","83","文本",""] const onlyNumbers = arr.filter((item) => typeof item === 'number')
这应该有效。