简体   繁体   中英

JavaScript nasted default parameters

Lets say I want to process some property x of objects in collection array . But collection may contain objects without such property or even undefined s. For example

let array = [
  {x: 1},
  {x: 2},
  {},
  {x: 4},
  undefined
]

The idea is protect my self from such edge cases with default parameter. Let it be 0 . I was trying to solve this as

array.map(({x: x = 0}) => process(x))

But it fails on undefined . Is there any way to solve this issue with default parameters and destructuring without writing check/set code inside of map function?

您可以为默认对象指定默认值

array.map(({x : x = 0} = 0) => process(x));

You can use .filter before .map in order to clean all falsy values like null , 0 , '' , false

array = array
    .filter((el) => el)
    .map(({x: x = 0}) => process(x));

Example

In MDN there is good description

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

so null is value., so if you pass null to function default value does not used, for example

function test(x = 10) {
    console.log(x);
}

test(undefined); // 10
test();          // 10
test(null);      // null
test(0);         // 0
test('');        // ''

Example

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