我正在使用 startsWithIgnoreCase 查询 dexie 数据库并将结果推送到一个数组中,但是在打印或使用它时,它抛出一个未定义的错误我尝试使用 JSON.stringify, toString, String 将其转换为字符串并在控制台上打印,但仍然显示未定义将整个数组打印到控制台显示正常的 Array()arr = [];db.table('friends').where('name').startsWithIgnoreCase('DoB/') .each(function (friend) { arr.push(String(friend.name)); });console.log(arr[0]); //undefined console.log(arr); //Array() with correct element inside当我使用 console.log(arr[0]) 时,我至少应该打印一些东西
1 回答

动漫人物
TA贡献1815条经验 获得超10个赞
从数据库调用数据是异步的,除非你告诉它,否则 javascript 不会等你直到你的任务完成。在您的查询中使用 async/await。像这样:
async myControllerFunction()=>{
arr = [];
let firends = await db.table('friends').where('name').startsWithIgnoreCase('DoB/')
.each(function (friend) {
arr.push(String(friend.name));
});
console.log(arr[0]);
console.log(arr);
}
添加回答
举报
0/150
提交
取消