创建对象时,如果值未定义,则不包含在新对象中
When creating an object, if a value is undefined don't include in the new object
主要是 es6/7 处理对象解构的问题。
假设我有这个示例函数:
const sample = (var1, var2) => {
const obj = {
one: var1
};
if (var2) {
obj.two = var2;
}
return obj;
};
这是一种说法,"the first argument is expected, if the 2nd argument is defined add it to the object too"。
是否有更优雅的方法来实现相同的效果但使用对象解构?
你也可以把你的函数写成
const sample = (one, two) => two? {one, two}: {one};
Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too"
与您的代码一样,请注意您作为第二个参数添加的值。
除了 undefined
之外,还有更多的虚假值,您可能希望将其中一些值分配给结果。如果条件是是否定义了第二个参数,我会明确检查 undefined
:
const sample = (one, two) => two !== undefined? {one, two}: {one};
主要是 es6/7 处理对象解构的问题。
假设我有这个示例函数:
const sample = (var1, var2) => {
const obj = {
one: var1
};
if (var2) {
obj.two = var2;
}
return obj;
};
这是一种说法,"the first argument is expected, if the 2nd argument is defined add it to the object too"。
是否有更优雅的方法来实现相同的效果但使用对象解构?
你也可以把你的函数写成
const sample = (one, two) => two? {one, two}: {one};
Its a way of saying, "the first argument is expected, if the 2nd argument is defined add it to the object too"
与您的代码一样,请注意您作为第二个参数添加的值。
除了 undefined
之外,还有更多的虚假值,您可能希望将其中一些值分配给结果。如果条件是是否定义了第二个参数,我会明确检查 undefined
:
const sample = (one, two) => two !== undefined? {one, two}: {one};