我創建了一個函式,它應該回傳一個包含用戶資料的物件。我希望函式接受一個物件作為引數,并且我希望這個物件在函式內部定義,所有值都預定義為默認引數,以防它們在函式呼叫時不傳遞。示例代碼只有 2 個值,但我需要超過 15 個。我怎樣才能實作這樣的解決方案?
const userCreator = (name, age) => {
if (name === undefined) {
name = 'John'
}
if (age === undefined) {
age = 25
}
return {
name:name,
age:age
}
};
uj5u.com熱心網友回復:
...而且我希望在函式內部定義這個物件,所有值都預定義為默認引數,以防它們在函式呼叫時不傳遞。
我想你是在說:
- 您希望函式接受一個物件
- 您希望該物件的所有屬性都是可選的,并具有函式指定的默認值
為此,您可以使用解構默認值。但另請參見下文,因為在這種特定情況下,您想要回傳一個物件,您可能需要使用不同的方法。
但是讓我們從沒有默認值的基本解構開始,然后添加它們:
const userCreator = ({ name, age }) => {
// ^???????????^???????????????? destructuring
// ...stuff with `name` and `age` here...
return {
name,
age,
};
};
要為這些屬性添加默認值,您可以將它們添加到解構模式中({}否則引數名稱所在的位置):
const userCreator = ({ name = "John", age = 25, }) => {
// ^^^^^^^^^?????^^^^^???? defaults for the properties
return {
name,
age,
};
};
如果有很多,可能最好分成幾行:
const userCreator = ({
name = "John",
age = 25,
}) => {
return {
name,
age,
};
};
不過,那個版本仍然希望提供一個物件。如果要允許userCreator()(根本不傳遞引數),則需要為物件引數添加默認引數值:
const userCreator = ({
name = "John",
age = 25,
} = {}) => {
//^^^^??????????????????????????? default for the parameter
return {
name,
age,
};
};
使用{}作為默認值,如果不帶任何引數都提供,"John"作為默認,如果name沒有提供,并25作為默認,如果age不提供。由于沒有name或age在默認值上{},所以當你這樣做時它們會被默認userCreator()。
替代方法:
既然你想回傳一個物件,你可以直接接受物件引數,然后使用屬性 spread 或Object.assign填充默認值,如下所示:
const userDefaults = {
name: "John",
age: 25,
};
const userCreator = (template) => {
const result = { // The result object we'll return
...userDefaults, // Fill in defaults
...template // Overwrite with any properties from the caller
};
// Or with `Object.assign` in older environments without property spread:
//const result = Object.assign(
// {}, // The result object we'll return
// userDefaults, // Fill in defaults
// template // Overwrite with any properties from the caller
//);
return result;
};
屬性傳播并且Object.assign都忽略nullor undefined,所以如果根本沒有傳遞物件,templateis undefined,和
uj5u.com熱心網友回復:
您應該直接在函式引數中定義默認值:
const userCreator = (name = 'John', age = 25) => {
return {
name: name,
age: age
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/366837.html
標籤:javascript 目的 默认参数
