如果我传递的数组为空,我需要将一个空对象设置为默认值。类似于:
var obj = { documents: [...question.documents] || [{}] }
我用一个条件修复了它,但是我想知道是否有更好的方法来实现这个目标。
if(obj.documents.length === 0) obj.documents.push({})
如果我传递的数组为空,我需要将一个空对象设置为默认值。类似于:
var obj = { documents: [...question.documents] || [{}] }
我用一个条件修复了它,但是我想知道是否有更好的方法来实现这个目标。
if(obj.documents.length === 0) obj.documents.push({})
有几种方法可以用单个表达式来编写此代码。
使用三元运算符:
var obj = { documents: [
...question.documents.length
? question.documents
: [{}]
]
};
var obj = { documents: [question.documents[0] || {}, ...question.documents.slice(1)] };
var obj = { documents: question.documents.length ? question.documents : [{}]}
or
子句,因为空数组也会返回真值。因此可以写成以下形式:-var obj = { documents: question.documents }
if(!obj.documents.length) obj.documents.push({})
由于即使是空数组也是真值,我认为除了在某个地方放置显式测试之外,没有任何优雅的解决方案。三元运算符比if
语句更简洁:
const question = { documents: [] };
const { documents } = question;
const obj = { documents: documents.length !== 0 ? documents : [{}]}
console.log(JSON.stringify(obj));
const question = { documents: [] };
const [firstElm = {}, ...otherElms] = question.documents;
const obj = { documents: [firstElm, ...otherElms] };
console.log(obj);
最短的方式
const obj1 ={...(true&& {x:1})};
console.log(obj1)
const obj2 ={...(false&& {y:1})};
console.log(obj2)
这应该适合...
const question = {
documents: [],
};
const obj = {
documents: [].concat(question.documents.length ? question.documents : {})
};
console.log(obj);