简体   繁体   中英

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 '. Not sure what's up. Any ideas?

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

in this line

i = i || 'random';

if i is true then value of i will be assigned else random will be used

try like this

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

call like this

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

0 is falsy.

I think you want to check if it's null or undefined :

 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:

 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.

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(); then

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

Try explicitly testing i for being undefined , or not. If i not undefined , return i , else return '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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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