使用变量存储“change.doc”路径

我正在尝试使用变量作为 firestore 文档路径:


        console.log(change.doc.data().m_1.name);   <----- This work well !


        a = 1;

        let me = change.doc.data().m_+a;    <----- But not that....

        console.log(me.name);

我怎样才能做到这一点 ?先感谢您 !:)


交互式爱情
浏览 144回答 3
3回答

海绵宝宝撒

使用动态属性时应该使用括号。let&nbsp;me&nbsp;=&nbsp;change.doc.data()['m_'&nbsp;+&nbsp;a];

蓝山帝景

我认为您想将键的名称构建为它自己的变量并使用它来索引对象。const a = 1;const key = "m_" + a;const me = change.doc.data()[key];

MMMHUHU

当您a在示例中使用变量时,您是在要求 JS 将数字 1 添加到您的函数输出中。这不是正确的方法。您想使用一个键来访问data()函数返回输出中的数据,如下所示。change = {doc: {&nbsp; &nbsp; data: function() {&nbsp; &nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; m_1: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: "Mario",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; occupation: "plumber",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; siblings: 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; age: 24&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; m_2: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; name: "Mike",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; occupation: "developer",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; siblings: 3,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; age: "28"&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }}console.log("Old way:" + change.doc.data().m_1.name);const a = 1;let me = change.doc.data()['m_' + a];console.log("Desired way: " + me.name)我假设了一个从您的问题派生的简单数据结构,但我不确定它是否是您所得到的。但它可能看起来有点像。编辑awww....页面没有刷新,我没有看到两个第一个答案:(好吧...至少我们同意
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript