Javascript 如何将值传递到节点中的数组中
嗨,我还在学习node,并尝试使用javascript nodejs做一些很酷的事情。 同时,当将单独的“where”sequelize语句传递到一个语句时,我被卡住了。 好的,这是我当前的代码:Javascript 如何将值传递到节点中的数组中,javascript,arrays,node.js,sequelize.js,koa,Javascript,Arrays,Node.js,Sequelize.js,Koa,嗨,我还在学习node,并尝试使用javascript nodejs做一些很酷的事情。 同时,当将单独的“where”sequelize语句传递到一个语句时,我被卡住了。 好的,这是我当前的代码: var periodsParam = {}; periodsParam = { delete: 'F', tipe: 1, variantid: (!ctx.params.id ? ctx.params.id :
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'}
我如何解决这个问题
任何帮助都将不胜感激,谢谢。问题是您总是在重新初始化它。应将其设置为现有对象的属性 更新自
periodsParam = {
country: ctx.query.country
};
到
问题是您总是在重新初始化它。应将其设置为现有对象的属性 更新自
periodsParam = {
country: ctx.query.country
};
到
也可以按如下方式指定对象:
periodsParam=Object.assign({},periodsParam,{country:ctx.query.country})代码>您也可以这样分配对象:
periodsParam=Object.assign({},periodsParam,{country:ctx.query.country})
问题是,您使用=
与periodsParam
签名3次,结果是periodsParam
只返回国家/地区,原因如下:
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;
}
正如建议的那样,条件应该是ctx.query&&ctx.query.country
-如果ctx.query
是未定义的则可以防止类型错误。问题是,您使用=
与periodsParam
签名3次,结果是periodsParam
只返回国家,由于这句话:
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;
}
根据建议,条件应该是ctx.query&&ctx.query.country
-如果ctx.query
是未定义的,则可以防止类型错误。顺便说一句:您不向数组中添加内容,而是向对象中添加内容。顺便说一句:您不向数组中添加内容,而是向对象中添加内容,此方法复制所有可枚举自身属性的值。首先,您不需要传递第一个参数{}
,因为您希望分配到periodsParam
:Object.assign(periodsParam,{country:ctx.query.country})代码>。另外,这个方法创建一个新对象,我们不需要它。为什么要创建一个新对象以将其分配给以前的变量?如中所述,此方法复制所有可枚举自身属性的值。首先,您不需要传递第一个参数{}
,因为您希望分配到periodsParam
:Object.assign(periodsParam,{country:ctx.query.country})代码>。另外,这个方法创建一个新对象,我们不需要它。为什么要创建一个新对象以将其分配给我们以前的变量?在尝试访问ctx.query.country
之前,还需要验证ctx.query
是否未定义,否则会出现类型错误:无法读取未定义的异常的属性“country”。它会导致if(ctx.query&&ctx.query.country){…}
。在尝试访问ctx.query.country
之前,您还需要验证ctx.query
是否未定义,否则将出现类型错误:无法读取未定义的异常的属性“country”。它的结果是if(ctx.query&&ctx.query.country){…}
。