简体   繁体   English

带可选参数的函数未注册传递的值

[英]Function with optional parameter not registering passed value

I have this function that has an optional parameter. 我有这个函数有一个可选参数。 The problem is that when I pass a parameter, it behaves as if I never passed it. 问题是,当我传递一个参数时,它的行为就像我从未传递过它一样。

Here's my code: 这是我的代码:

function sideA(i){

    // i is an optional argument.
    i = i || 'random';

    console.log(i);
}

sideA(0);

Here, the console will always display ' random '. 在这里,控制台将始终显示“ random ”。 Not sure what's up. 不确定是什么。 Any ideas? 有任何想法吗?

0,"",undefined,null treat as false . 0,"",undefined,null视为false

in this line 在这一行

i = i || 'random';

if i is true then value of i will be assigned else random will be used 如果我是真的那么i的值将被分配,否则将被使用

try like this 试试这样

 i= typeof i ===  "undefined" ? "random" : i

call like this 像这样打电话

sideA(0) 
sideA() // pass nothing to get random

0 is falsy. 0是假的。

I think you want to check if it's null or undefined : 我想你想检查它是否为nullundefined

 function sideA(i) { // i is an optional argument. i = (i === null || i === undefined ? 'random' : i); console.log(i); } sideA(0); 

Alternatively, you can check the typeof to see if it is a number: 或者,您可以检查typeof以查看它是否为数字:

 function sideA(i) { // i is an optional argument. i = (typeof i === 'number' ? i : 'random'); console.log(i); } sideA(0); 


Documentation: 文档:

It is because 0 is a falsy value , so the Logical OR operator will return the second operand. 这是因为0是一个假值 ,因此Logical OR运算符将返回第二个操作数。

If you want to use which ever value is passed, if any even undefined but want to use a default value if no argument is used like sideA(); 如果你想使用哪个值传递,如果有任何甚至未定义但是如果没有使用参数,则想要使用默认值,如sideA(); then 然后

i = arguments.length ? i : 'random';

Try explicitly testing i for being undefined , or not. 尝试明确地测试i是否undefined If i not undefined , return i , else return 'random' 如果i没有undefined ,请返回i ,否则返回'random'

  function sideA(i) { // i is an optional argument. // if `i` _not_ `undefined` , `i` = `i` , // else , `i` = `'random'` i = i !== undefined ? i : 'random'; console.log(i); } sideA(0); 

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

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