[英]How can I make sure only string and number arguments can be passed?
How can I check to see if my arguments are strings or numbers only?如何检查我的 arguments 是字符串还是数字?
Task 4 - find the smallest number in a list.任务 4 - 找到列表中的最小数字。 Allow any number of arguments to be passed to the function.
允许将任意数量的 arguments 传递给 function。 Allow both String and Number arguments to be passed, but throw an error if any other type is passed to the function (eg, Boolean, Date, etc.).
允许同时传递字符串和数字 arguments,但如果将任何其他类型传递给 function(例如 Boolean、日期等),则会引发错误。 If the list is empty (nothing passed to the function), return Number.MIN_VALUE,
如果列表为空(没有传递给函数),返回 Number.MIN_VALUE,
<script>
highAndLow =(... numbers) => {
if(numbers.length<=0){
return Number.MIN_VALUE;
}
if (typeof numbers !== 'string' || (isNaN(numbers)===true)){
throw new Error('Whoops!, Only String and Numbers allowed');
}else{
numbers = numbers + '';
var smallestElement = numbers[0];
numbers = numbers.split(' ');
for (var i = 0; i < numbers.length; i++) {
if (+numbers[i] < +smallestElement) {
smallestElement = numbers[i];
}
}
}
return ` ${smallestElement}`;
};
console.log(highAndLow('4 5 29 54 4 0 -214 542 -64 1 -3 6 12'));
alert(highAndLow('4 5 29 54 4 0 -214 542 -64 1 -3 6 12'));
</script>
You need to do the type checking inside the loop.您需要在循环内进行类型检查。
typeof numbers[i] !== 'string' || (isNaN(numbers[i])===true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.