【问题标题】:Replace a number/string with a variable用变量替换数字/字符串
【发布时间】:2020-03-31 03:26:03
【问题描述】:

我正在使用以下正在运行的代码向 Firebase 发送数据:

var mac = "10:10:10:10";
var ref = rootRef.child('user/' + 'nicolas');

if(pass == "4920" ){
 ref.update({
   1: mac
 });
}  

我需要做的是用变量替换“1”,因为我需要动态地更改值。我尝试了以下方法:

var mac = "10:10:10:10";
var ref = rootRef.child('user/' + 'nicolas');
var index = 1;

if(pass == "4920" ){
 ref.update({
   index: mac
 });
}  

但结果是mac地址存储在“index”目录中,没有名为“1”的目录。谢谢。

【问题讨论】:

标签: javascript jquery html firebase firebase-realtime-database


【解决方案1】:

只需将变量名放在括号内,它就会被解析为实际变量

if(pass == "4920" ){
      ref.update({
      [index]: mac
    });
   } 

【讨论】:

    【解决方案2】:

    实时数据库并没有真正的“目录”。它有嵌套节点。如果您想继续在ref 下嵌套更多节点,您可以通过调用 child() 继续添加它们。

    var ref = rootRef.child('user/' + 'nicolas');
    var indexRef = ref.child('1');
    indexRef.update(mac);
    

    如果你想传递一个具有变量值的键的对象,你可以使用 JavaScript 语法(这与 Firebase 无关):

    ref.update({
       [index]: mac
    });
    

    【讨论】:

      猜你喜欢
      • 2020-07-09
      • 2011-09-29
      • 2013-02-16
      • 2017-06-21
      • 2018-01-01
      • 2014-12-11
      • 1970-01-01
      • 1970-01-01
      • 2017-04-06
      相关资源
      最近更新 更多