gpt4 book ai didi

javascript - 尝试迭代 Map 元素时出现 TypeError

转载 作者:行者123 更新时间:2023-11-28 13:00:36 25 4
gpt4 key购买 nike

我试图迭代我认为是 Map 对象的元素并收到以下错误:

TypeError: cr.forEach is not a function
at exports.onNewOrder.functions.database.ref.onCreate.event (/user_code/index.js:122:12)
at Object.<anonymous> (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:112:27)
at next (native)
at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:28:71
at __awaiter (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:24:12)
at cloudFunction (/user_code/node_modules/firebase-functions/lib/cloud-functions.js:82:36)
at /var/tmp/worker/worker.js:728:24
at process._tickDomainCallback (internal/process/next_tick.js:135:7)

这是我在 Google Cloud Function 中运行的代码:

function logMapElements(value, key, mapObj) {
console.log(`m[${key}] = ${value}`);
}

exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {

const data = event.val();
const cr = data.crs;
console.log(cr);

cr.forEach(logMapElements);
}

这是 console.log(c) 在日志中打印的内容:

{ cr_36446aba912c45d0956e57cbf0a4e165: 1, cr_d46f4c12119e45478a0aa2867df55e09: 1 }

我在这里做错了什么?

最佳答案

虽然 Sidhanshu_、user9977547 和 Fabien Greard 的答案都可能有效,但我考虑使用 Firebase 的内置 DataSnapshot.forEach更惯用的方法:

exports.onNewOrder = functions.database.ref('/orders/{orderId}').onCreate(event => {
event.child("crs").forEach(child => {
console.log(child.val());
});
}

而结果在Array.forEach()之间和DataSnapshot.forEach()这里是一样的,在其他一些情况下有细微的差别。当您从 Firebase 数据库查询数据时,DataSnapshot.forEach()将按照请求的顺序迭代子级,而当您到达 Array.forEach() 时,您通常会丢失该顺序。 。为了避免细微的错误,我建议使用 DataSnapshot.forEach()用于 Firebase 数据库中的任何数据。

关于javascript - 尝试迭代 Map 元素时出现 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com