【问题标题】:How to pass value into array in node如何将值传递给节点中的数组
【发布时间】:2018-03-20 10:35:28
【问题描述】:

嗨,我还在学习 node 并尝试使用 javascript nodejs 做一些很酷的事情。 同时,当将单独的“where”sequelize 语句合并为一个时,我被卡住了。 好的,这是我当前的代码:

var periodsParam = {};
        periodsParam = {
            delete: 'F',
            tipe: 1,
            variantid: (!ctx.params.id ? ctx.params.id : variants.id)
        };

        if (ctx.query.country) {
            periodsParam = {
                country: ctx.query.country
            };
        }

        console.log(periodsParam);

从上面的代码,它总是返回 { country: 'SG' } ,但我想返回 { delete: 'F', tipe: 1, variantid: 1, country: 'SG' }

我该如何解决?

任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 顺便说一句:你不会向数组添加东西,而是向对象添加东西。

标签: javascript arrays node.js sequelize.js koa


【解决方案1】:

问题是,您使用 = 符号和 periodsParam 3 次,而您最终得到 periodsParam 只返回 country,因为这行:

if (ctx.query.country) {
  periodsParam = {
    country: ctx.query.country
  };
}

不要将新对象分配给periodsParam,而是使用点表示法添加另一个键值对,如下所示:

if (ctx.query && ctx.query.country) { //before accesing .country check if ctx.query is truthy
  periodsParam.country = ctx.query.country;
}

正如@Paul 建议的那样,条件应该是ctx.query && ctx.query.country - 如果ctx.query 是undefined,它将防止TypeError。

【讨论】:

  • 在尝试访问ctx.query.country 之前,您还需要验证ctx.query 是否未定义,否则您将遇到TypeError: Cannot read property 'country' of undefined 异常。结果为if (ctx.query && ctx.query.country) { ... }。
【解决方案2】:

问题是你总是重新初始化它。您应该将其设置为现有对象的属性。

更新自

periodsParam = {
    country: ctx.query.country
};

到

periodsParam.country = ctx.query.country;

【讨论】:

    【解决方案3】:

    你也可以像这样分配对象:

    periodsParam = Object.assign({}, periodsParam, { country: ctx.query.country });

    【讨论】:

    • 如MDN web docs - Object.assign() 中所述,此方法复制所有可枚举自身属性的值。首先,您不需要传递第一个参数{},因为您要分配给periodsParam:Object.assign(periodsParam, { country: ctx.query.country });。此外,此方法创建一个新对象,我们不需要它。为什么要创建一个新对象来将其分配给我们之前的变量?
    猜你喜欢
    • 2015-11-25
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2017-10-18
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多