我尝试了以下方法以获得这种效果:
const query1 = await db.all(SQL`SELECT * FROM list WHERE name = ${user}`);
const result = query1 ? typeof query1 === 'object' && typeof query1.reason === 'string' ? `✅\n${query1.reason}` : '✅\nNo reason available' : '❌';
query1的输出是:
[ { id: 2542, name: 'Mesa', reason: 'test' } ]
但是我总是得到:✅没有可用的理由,要使其正常运行,我必须更改什么?
答案 0 :(得分:1)
您正在if语句中寻找query1
和query1.reason
,但这是错误的。 query1
是一个保存对象项的数组(对于SQL db,每个返回一个对象)。因此,您应该寻找query1[0]
和query1[0].reason
来建立它。
请注意,typeof query1
仍会输出'object'结果,因为数组也是javascript中的Objects。
修改
好吧,烦人的长行让我也错过了文字if语句中的另一个错误。您正在使用两个:
运算符。我将假设您的意思是类似if, else if, else
的东西,但是使用1个衬里是不可能的。这只是一种if, else
操作。
您可以在if/else
运算符之后嵌套另一个:
语句。
这样的示例代码:
const q1 = [ { id: 2542, name: 'Mesa', reason: 'test' } ];
const q2 - [];
const q3 = [ { id: 2542, name: 'test'} ]
function getRes(q){
const res = typeof q[0] == 'object' && typeof q[0].reason == 'string' && q.length > 0 ? console.log("got result with reason string") : (q.length > 0) ?console.log("got result but not reason string") : console.log("got no result")
return res;
}
getRes(q1) // console output: got result with reason string
getRes(q2) // console output: got no result
getRes(q2) // console output: got result but not reason string
如何
这是非常烦人的代码,并且如果有人日后需要维护它,将会非常烦人,难以理解。我肯定会使用常规的if(){},else if{}, else
选项。
答案 1 :(得分:0)
由于查询返回array
,因此您需要检查该数组中的项目,而不是数组本身。
const query = [ { id: 2542, name: 'Mesa', reason: 'test' }, { id: 2543, name: 'Mesa2', reason: undefined } ]
for(let data of query){
const result = typeof data.reason === 'string' ? `✅\n${data.reason}` : '✅\nNo reason available';
console.log(data)
console.log(result)
}