![](/img/trans.png)
[英]Javascript generator to generate prime numbers less than a given number
[英]Javascript return number less than 100 given an array with numbers and strings
如下所示,我该如何编写一个返回小于100的数字的函数?
const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false]
const isLessThan100 = (array) => {
// how to do this? Solution enter here
}
我认为它涉及filter方法,但是我不确定如何同时过滤小于100的数字和不是字符串的数字。
提前致谢!
您可以先检查它是否是数字
const myArray = ['hello', 3, true, 18, 10, 99, 'ten', false];
const isLessThan100 = myArray.filter(item => {
return (typeof item === "number") && item < 100;
});
typeof运算符返回一个字符串,该字符串指示未评估的操作数的类型。
你可以先检查是否typeof
的产品number
或没有,然后检查它是否小于100
。
您可以通过删除花括号将代码减少到一行。
尝试使用Array.prototype.filter()
,方法如下:
const myArray = ['hello', 3, true, 18, 10,, 99, 'ten', false] const isLessThan100 = (array) => array.filter(num => typeof(num) === "number" && num < 100); console.log(isLessThan100(myArray))
const isLessThan100 = (array)
这是一个使用filter的矮个子:
const myArray = ['hello', 3, true, 18, 10, 99, 101, 'ten', false]; const isLessThan100 = a => a.filter(e => +e === e && e < 100); console.log(isLessThan100(myArray));
为了只获取一个值,可以减少数组。
const array = ['hello', 3, true, 18, 10,, 99, 'ten', false], isLessThan100 = array => array.reduce((r, v) => typeof v === 'number' && v < 100 && (typeof r !== 'number' || v > r) ? v : r, undefined); console.log(isLessThan100(array));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.