猿问

如何在Javascript中使用命名参数的默认值

我有一个 javascript 函数,它将对象作为参数,如下所示:

const someFunc = ({ a }) => { <do something> }

我这样调用函数:

a = 'some value'
someFunc({ a })

但有时,我需要调用函数而不传递a. 在这种情况下,我需要为a. 如何为对象内的键添加默认值?


神不在的星期二
浏览 102回答 4
4回答

白衣非少年

我认为您正在寻找默认参数const someFunc = ({ a = "foo" }) => {&nbsp; &nbsp;console.log(a);}someFunc({}); // "foo"someFunc({a: "bar"}); // "bar"更新 如果您还希望在不传递任何参数的情况下将其设为默认值,a则还需要为包含. 就像是:"foo"aconst someFunc = ({ a = "foo" } = {}) => {&nbsp; &nbsp;console.log(a);}someFunc(); // "foo"

弑天下

ES6 接受参数的默认值:const someFunc = ({a} = {a : 6}) => {&nbsp;&nbsp; console.log({a})}someFunc({ a : 3 })someFunc()

哈士奇WWW

const someFunc = ({a, b, c ,d} = {a:10, b: 12, c:3, d:4}) => {&nbsp; &nbsp;console.log(a, b, c ,d);}someFunc()请记住,此代码实际上不会在 IE 中工作。这是 IE 的解决方法:&nbsp; &nbsp; var someFunc = function someFunc() {&nbsp; &nbsp; var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {&nbsp; &nbsp; &nbsp; &nbsp;a: 10&nbsp; &nbsp; },&nbsp; &nbsp; a = _ref.a;&nbsp; &nbsp; //here starts the function&nbsp; &nbsp; console.log(a);};someFunc();

慕田峪4524236

const someFunc = ({ a }) => {&nbsp;&nbsp;typeof a === 'undefined'&nbsp;&nbsp;? a = 'some default'&nbsp;: a = a;&nbsp;console.log(a);}a = 'some value';someFunc({ a });someFunc({});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答