我想创建一个函数,它返回一个对象。有时,该函数的一个参数是空字符串。如果我仅在函数参数不是空字符串时放置 if 语句来生成对象属性: city.length > 0 ? 'city': city :
它会抛出错误。知道如何在对象内正确定义 if
语句吗?
function generateJson(city, state) {
return {
city.length > 0 ? 'city': city : ,
state.length > 0 ? 'state': state :
};
}
let city = 'NY';
let state = '';
generateJson(city, state); //output: { 'city': 'NY' }
最佳答案
这将生成一个 JSON。要转换为 JS 对象,只需使用 JSON.parse
。
function generateJson(city, state) {
return JSON.stringify({
city: city.length > 0 ? city : undefined,
state: state.length > 0 ? state: undefined,
});
}
let city = 'NY';
let state = '';
console.log(generateJson(city, state)); //output: { 'city': 'NY' }
关于javascript - 使用 if 语句创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44343905/