从数组中过滤数字 [英] Filtering numbers out from an array

查看:64
本文介绍了从数组中过滤数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组,需要从中过滤出数字: [1,2]

I have an array like below and need to filter out the numbers from it ex: [1,2]

var str = [
  "https://xx.jpg",
  "https://xx.jpg",
  "1",
  "https://guide.jpg",
  "2", 
  "/static.jpg"
]

我有以下代码:

var filtered = str.filter(function(item) {
  return (typeof item === "number")
});

但它没有过滤,因为它是一个字符串。

but it is not filtering as it is a string.

怎么做?

推荐答案

做一个小改动你的代码可以使它工作,这可能会有效。

Making a small change to your code to make it work, this might possibly work.

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
  return !(parseInt(item) == item);
});
console.log(filtered);

或者如果你想要数字:

var str = ["https://xx.jpg", "https://xx.jpg", "1", "https://guide.jpg", "2", "/static.jpg"];
var filtered = str.filter(function (item) {
  return (parseInt(item) == item);
});
console.log(filtered);

这篇关于从数组中过滤数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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