简体   繁体   English

如何使用JavaScript从数组中删除\\'a \\'等值

[英]How do I remove values like \'a\' from an array with javascript

I am stuck at this challenge on codewars where I have to return only numbers from an array as a new array and neglect all non-numbers. 我陷入代码战的挑战,我只需要将数组中的数字作为新数组返回,而忽略所有非数字。

I was presented with something like this ['1', '2', \\'a\\', \\'b\\']. 呈现给我的东西是这样的['1','2',\\'a \\',\\'b \\']。 This is meant it return just [1, 2] 这意味着它只返回[1,2]

I tried this. 我试过了

function filter_list(l) {
    return l.filter(c => c>=0 && c <= 999)
} 

I got my [1, 2] in the case of this ['1', '2', \\'a\\', \\'b\\'] but got a [\\'1\\'] in the case of [\\'1\\'] instead of [] 我有我的[1, 2]在这种情况下['1', '2', \\'a\\', \\'b\\'] ,但有一个[\\'1\\']中的情况下[\\'1\\']代替[]

What do I do? 我该怎么办?

You need to check if the elements are actually numbers or if they are strings containing numbers. 您需要检查元素实际上是数字还是它们是包含数字的字符串。 Here are a couple of solutions using filter: 以下是使用过滤器的几种解决方案:

function num (arr) {
  return arr.filter(c => Number.isInteger(c));
}

function num2 (arr) {
  return arr.filter(c => typeof c === 'number');
}

Check out these resources: 查看以下资源:

Number.isInteger()- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger Number.isInteger()-https: //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger

typeof- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof typeof- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof

this should work ( if you pass an array without the backslashes like [1,'2','a'] ) 这应该工作(如果您传递不带[1,'2','a']等反斜杠的数组)

function filter_list(l) {
    return l.filter(c => parseInt(c) >=0 && parseInt(c) <= 999)
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM