[英]Javascript return number less than 100 given an array with numbers and strings
Given below, how do I write a function that will return a number less than 100? 如下所示,我该如何编写一个返回小于100的数字的函数?
const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false]
const isLessThan100 = (array) => {
// how to do this? Solution enter here
}
I think it involves the filter method, but im not sure how to filter both a number less than 100, and is not a string. 我认为它涉及filter方法,但是我不确定如何同时过滤小于100的数字和不是字符串的数字。
Thanks in advance! 提前致谢!
you can check if it is a number first like this 您可以先检查它是否是数字
const myArray = ['hello', 3, true, 18, 10, 99, 'ten', false];
const isLessThan100 = myArray.filter(item => {
return (typeof item === "number") && item < 100;
});
The typeof operator returns a string indicating the type of the unevaluated operand. typeof运算符返回一个字符串,该字符串指示未评估的操作数的类型。
You can first check whether the typeof
the item is number
or not, then check if it is less than 100
. 你可以先检查是否typeof
的产品number
或没有,然后检查它是否小于100
。
You can reduce the code to a single line by removing the curly braces. 您可以通过删除花括号将代码减少到一行。
Try Array.prototype.filter()
like the following way: 尝试使用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)
For getting only a single value, you could reduce the array. 为了只获取一个值,可以减少数组。
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.