简体   繁体   English

如何确保只能传递字符串和数字 arguments?

[英]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.

相关问题 如何确保没有 arguments 传递给 function - How to make sure no arguments are passed to a function 如何确保一次只打开/展开 1 个面板? - How can I make sure only 1 panel is open/expanded at a time? 如何确保在frisby.js中的post方法上传递标头cookie - how can I make sure the header cookie is passed on a post method in frisby.js 函数参数可以传递给字符串吗? - Can function arguments be passed into a string? 如何确保我的 PHP api 只能由特定的 javascript 页面使用 - How can I make sure that my PHP api can only be used by a specific javascript page 如何确保在输入字段中输入新数字时脚本/<p> 标签刷新? - How can I make sure when I put a new number in input field the script/ <p> tag refreshes? 如何制作可以过滤字符串和数字值的Scfilter? - How can i make a Scfilter that can filter string and number values? 我怎样才能确保这个 function 将返回一个没有任何重复的数组,并且不减少元素的数量? - How can I make sure this function will return an array without any duplicates, and without reducing the number of elements? 如何确保 function 只运行一次并触发多个绑定和事件? - How can I make sure a function only runs once with multiple bindings and events firing? 如何确定文本框中的字符仅是1,而二进制是0? - How can I make sure that whaveter is in the text box is only 1's and 0's for binary?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM