如何在javascript中过滤数组? [英] How to filter an array in javascript?

查看:189
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆