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

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

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