如何在javascript中过滤数组? [英] How to filter an array in javascript?
问题描述
这是一个数组,
total = [10%,1000,5%,2000]
。我怎么能过滤这两个数组像百分比= [10%,5%]和绝对= [1000,2000]使用JavaScript数组过滤器。
回调函数
函数。 / b>
filter()方法创建一个新的数组,其中包含所有通过
的元素。 >
另外,使用 typeof
运算符数组的项目类型。 typeof 运算符返回一个字符串,指示未评估的操作数的类型。
let total = [10%,1000,5%,2000]; let percentage = total.filter(function(item){return typeof item =='string'& amp; ;& item.includes('%');}); console.log(percentage); let absolute = total.filter(function(item){return typeof item =='number'||!isNaN(item); }); console.log(absolute);
This is an array,
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.
You should use filter
method, which accepts a callback
function.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
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屋!