尝试为数据库搜索结果创建一行



我尝试了以下方法来获得此效果:

  • 如果没有行,则显示 ❌
  • 如果有一行但没有原因,则显示✅"无可用原因">
  • 如果有一行和原因,则显示✅和原因

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' : '❌';

查询 1 的输出为:

[ { id: 2542, name: 'Mesa', reason: 'test' } ]

但是我总是得到:✅没有可用的理由,我必须更改什么才能使其工作?

您正在if语句中查找query1query1.reason,但这被误导了。query1是一个保存对象项的数组(对于 SQL 数据库,每个对象可能返回 1 个对象(。因此,您应该寻找query1[0]query1[0].reason以建立它。

请注意,typeof query1仍然输出一个"对象"结果,因为数组也是 javascript 中的对象。

编辑

好吧,烦人的长线让我也错过了您的文字 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选项。

由于该查询返回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)
}

最新更新