Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 数组的许多特定对象属性_Javascript_Node.js_Express_Node Sqlite3 - Fatal编程技术网

Javascript 数组的许多特定对象属性

Javascript 数组的许多特定对象属性,javascript,node.js,express,node-sqlite3,Javascript,Node.js,Express,Node Sqlite3,我在我的express应用程序中使用sqlite3,当用户向我的系统添加新帐户时,我使用以下代码向数据库添加信息: db.run(`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, [this.uuid, this.email, this.pass, this.device, this.user, this.pet, th

我在我的express应用程序中使用sqlite3,当用户向我的系统添加新帐户时,我使用以下代码向数据库添加信息:

db.run(`INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
    [this.uuid, this.email, this.pass, this.device, this.user, this.pet, this.gold, this.is_active],
    function (err) {
        if (err) {
            return console.log(err.message);
        }
    });
db-是我的sqlite3实例

我相信应该有一种更好的编码方法(可能是一些带有spread的东西?)。
但我不知道如何只从“this”(它包含我数据库中不需要的其他属性)中获取特定属性。

您可以创建一个属性数组,从
中提取该
,然后
.map
它:

const props = 'uuid email pass device user pet gold is_active'.split(' ');
db.run(
  `INSERT INTO accounts(uuid, email, pass, device, user, pet, gold, is_active) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
  props.map(prop => this[prop]),
  function(err) {
    if (err) {
      return console.log(err.message);
    }
  }
);
通过保存属性字符串,您可以对其进行拆分并将其传递到
的第一个参数,从而可以减少重复性(并且更不容易出错)。运行

const propsStr = 'uuid, email, pass, device, user, pet, gold, is_active';
const props = propsStr.split(', ');
db.run(
  `INSERT INTO accounts(${propsStr}) VALUES(${propsStr.replace(/\w+/g, '?')})`,
  props.map(prop => this[prop]),
  function(err) {
    if (err) {
      return console.log(err.message);
    }
  }
);

也许在第一个示例中添加props.join(‘,’)来添加它,就像
INSERT-INTO-accounts(${props.join(‘,’)})值(?,,,,,,,,,,,,,,,?)
,也可以使用
值(${Array(props.length)。填充(“?”).join(“,”)
,这样你就不必计算和键入所有的问号了。我也这么认为。非常感谢你们!