简体   繁体   English

检查功能参数的简便方法

[英]Shorthand way to check for function parameters

In my code, I have a function that creates a new map given a few parameters. 在我的代码中,我有一个函数,可以在给定一些参数的情况下创建一个新地图。 I want to make it so that if no parameters are passed, some default values will be used. 我想这样做,以便如果不传递任何参数,将使用一些默认值。

Why won't this work: 为什么不起作用:

 function create(a,b,c) {
   return new Map(a,b,c || 10,1,10); // create new map using a b c as parameters
   // or 10, 1, 10 if none entered.
}

 create();

Assume that there is a constructor function 'Map' that would accept and process these parameters. 假设有一个构造函数“ Map”将接受并处理这些参数。

What can i do besides having an if/else type check? 除了进行if / else类型检查外,我还能做什么?

You can do it this way: 您可以这样操作:

function create(a, b, c) {
     a = typeof a !== 'undefined' ? a : 10;
     b = typeof b !== 'undefined' ? b : 1;
     c = typeof c !== 'undefined' ? c : 10;
     return new Map(a, b, c);
}

Javascript does not offer default function value parametization. Javascript不提供默认的函数值参数化。

The shortest way i know under some limitations is to use 在某些限制下,我知道的最短方法是使用

<var> = <var> || <defaultvalue>;

So 所以

Return new Map((a = a || 10), (b = b || 1), (c = c || 10));

However this way its hardly readable and you might want to consider moving the assignments before the constructor. 但是,这种方式很难理解,您可能需要考虑将分配移到构造函数之前。

The limitation however is that all falsy values lead to the default being assigned which might be a problem for some numeric values. 但是,限制是所有伪造的值都会导致分配默认值,这对于某些数字值可能是个问题。

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

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