Ste*_*eve 3 javascript arrays 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);
});
Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)