我在这样的for循环中有一个数组:
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
我只需要这样的数字:
var arr = ["5","2","2"];
所以有人可以帮忙吗?
答案 0 :(得分:3)
另一种方法是将转换后的数字转换为字符串并与原始值进行比较。
var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
result = array.filter(v => (+v).toString() === v);
console.log(result);
使用isFinite
var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
result = array.filter(isFinite);
console.log(result);
虽然标有underscore.js,但您可以使用下划线进行过滤和回调。
var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
result = _.filter(array, _.isFinite);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
答案 1 :(得分:1)
filter
将强制转换为整数的字符串替换为一个字符串:
var arr = ["abc", "5", "city", "2", "", "area", "2", "max", "choice"];
const out = arr.filter(el => (
el !== '' && Number.isInteger(Number(el)))
);
console.log(out)
答案 2 :(得分:0)
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
const filtered = arr.filter(item => !isNaN(item));
console.log(filtered);
答案 3 :(得分:0)
您可以将filter
方法与isNaN
函数var numbers = arr.filter(c=> !isNaN(c));
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
var numbers = arr.filter(c=> !isNaN(c));
console.log(numbers);
答案 4 :(得分:0)
使用forEach
循环并使用isNaN()
var arr = ["abc", "5", "city", "2", "area", "2", "max"];
var a=[];
arr.forEach(e=>isNaN(e)?true:a.push(e))
console.log(a)