如何在javascript中过滤数组? [英] How to filter an array in javascript?
问题描述
这是一个数组,
total = ["10%", 1000, "5%", 2000]
.我如何将它们过滤成两个数组,例如百分比 = ["10%","5%"] 和绝对 = [1000,2000] 使用 javascript 数组过滤器.
total = ["10%", 1000, "5%", 2000]
. how can i filter these into two array like, percentage = ["10%","5%"] and absolute = [1000,2000] using javascript array filter.
推荐答案
你应该使用 filter
方法,它接受一个 callback
函数.
You should use filter
method, which accepts a callback
function.
filter() 方法创建一个包含所有通过的元素的新数组由提供的函数实现的测试.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
另外,使用 typeof
operator 来从数组中找出项目的类型.typeof 运算符返回一个字符串,指示未计算的操作数的类型.
Also, use typeof
operator in order to find out the type of item from array. The typeof operator returns a string indicating the type of the unevaluated operand.
let total = ["10%", "1000", "5%", "2000"];
let percentage = total.filter(function(item){
return typeof item == 'string' && item.includes('%');
});
console.log(percentage);
let absolute = total.filter(function(item){
return typeof item == 'number' || !isNaN(item);
});
console.log(absolute);
这篇关于如何在javascript中过滤数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!