我有一个 JavaScript 函数,它以这样的形式作为参数接受一个对象:
const someFunc = ({ a }) => { <do something> }
我这样调用函数:
a = 'some value'
someFunc({ a })
但有时候,我需要在不传递a
的情况下调用该函数。在这种情况下,我需要为a
使用默认值。如何在对象内为一个键添加默认值?
我有一个 JavaScript 函数,它以这样的形式作为参数接受一个对象:
const someFunc = ({ a }) => { <do something> }
我这样调用函数:
a = 'some value'
someFunc({ a })
但有时候,我需要在不传递a
的情况下调用该函数。在这种情况下,我需要为a
使用默认值。如何在对象内为一个键添加默认值?
我认为你正在寻找 默认参数
const someFunc = ({ a = "foo" }) => {
console.log(a);
}
someFunc({}); // "foo"
someFunc({a: "bar"}); // "bar"
更新
如果你想要a
默认为"foo"
而无需传递任何参数,你需要为包含a
的对象设置一个默认参数。就像这样:
const someFunc = ({ a = "foo" } = {}) => {
console.log(a);
}
someFunc(); // "foo"
未捕获的类型错误:无法读取未定义的属性'a'
。 - Jeremy ThillesomeFunc()
调用中添加任何对象。如果OP想要在不传递任何内容的情况下调用 someFunc
,函数签名应该包括这一点。 - ZER0a
是属性,而不是对象。这就是我回答的问题。如果他想要整个对象,我编辑了我的答案以涵盖该场景。但这不是他写的。 - ZER0ES6支持为参数设置默认值:
const someFunc = ({a} = {a : 6}) => {
console.log({a})
}
someFunc({ a : 3 })
someFunc()
someFunc({})
呢?如果对象内有多个键可能需要这样做。 - Yedhu KrishnansomeFunc = (obj = {a : 6})
,则可以将任何对象传递给该函数。如果答案对您有帮助,请不要忘记将其标记为已接受! - Jeremy Thilleconst someFunc = ({a, b, c ,d} = {a:10, b: 12, c:3, d:4}) => {
console.log(a, b, c ,d);
}
someFunc()
请记住,这段代码在IE中实际上不会生效。
以下是适用于IE的解决方法:
var someFunc = function someFunc() {
var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
a: 10
},
a = _ref.a;
//here starts the function
console.log(a);
};
someFunc();
someFunc({})
这样调用它怎么办?如果对象内有多个键,则可能需要这样做。 - Yedhu KrishnansomeFunc({})
,它将不起作用。在这里,我传递了一个空对象而不是什么都没有传递。 - Yedhu Krishnanconst someFunc = ({ a }) => {
typeof a === 'undefined'
? a = 'some default'
: a = a;
console.log(a);
}
a = 'some value';
someFunc({ a });
someFunc({});
a = a === undefined ? "default" : a
而不是滥用赋值表达式。您能解释一下为什么这比现有答案更可取吗? - ggorlen