需要从数组中删除字符串
Need to remove string from an Array
我在 for 循环中有一个数组,如下所示:
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
我只需要这样的数字:
var arr = ["5","2","2"];
所以请有人帮忙。
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
const filtered = arr.filter(item => !isNaN(item));
console.log(filtered);
您可以使用 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);
filter
将整数强制转换为整数时的字符串:
var arr = ["abc", "5", "city", "2", "", "area", "2", "max", "choice"];
const out = arr.filter(el => (
el !== '' && Number.isInteger(Number(el)))
);
console.log(out)
使用 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)
另一种方法是将数字转换为字符串并与原始值进行比较。
var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
result = array.filter(v => (+v).toString() === v);
console.log(result);
的方法更短
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>
我在 for 循环中有一个数组,如下所示:
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
我只需要这样的数字:
var arr = ["5","2","2"];
所以请有人帮忙。
var arr = ["abc", "5", "city", "2", "area", "2", "max", "choice"];
const filtered = arr.filter(item => !isNaN(item));
console.log(filtered);
您可以使用 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);
filter
将整数强制转换为整数时的字符串:
var arr = ["abc", "5", "city", "2", "", "area", "2", "max", "choice"];
const out = arr.filter(el => (
el !== '' && Number.isInteger(Number(el)))
);
console.log(out)
使用 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)
另一种方法是将数字转换为字符串并与原始值进行比较。
var array = ["abc", "5", "city", "2", "area", "2", "max", "choice"],
result = array.filter(v => (+v).toString() === v);
console.log(result);
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>