变量值在nodeJS中意外更改

时间:2018-12-14 00:49:11

标签: node.js

let fulfillmentMessages = []
let multipleRides = formats.text_message
multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response

console.log("Multiple rides Message")
console.log(JSON.stringify(multipleRides))

let noRides = formats.text_message;
noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response;

console.log("Multiple rides Message after")
console.log(JSON.stringify(multipleRides))

fulfillmentMessages.push(multipleRides)
fulfillmentMessages.push(noRides)

console.log("Going to send these messages")
console.log(JSON.stringify(fulfillmentMessages))

在此代码执行之后,MultipleRides和noRides中具有相同的值,并且数组两次包含相同的值。有人可以在这里解释我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

这里的主要问题是multipleRidesnoRides这两个变量都引用相同的对象formats.text_message,因此multipleRides.payload.data与{{ 1}}。因此,noRides.payload.data中的赋值将覆盖multipleRides.payload.data.text中存储的值。在JavaScript中,对象是按引用而不是按值复制的。您将需要进行noRides.payload.data.text的深层克隆。由于formats.text_message的深度,浅表副本是不够的。

This article将为您提供一些进行深度克隆的提示。我的建议是使用lodash ,代码将是:

text

您也可以使用const _ = require('lodash') let fulfillmentMessages = [] let multipleRides = _.cloneDeep(formats.text_message) multipleRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes.case_ids.response console.log("Multiple rides Message") console.log(JSON.stringify(multipleRides)) let noRides = _.cloneDeep(formats.text_message); noRides.payload.data.text = predefined_responses.intent_report_lost_credential_confirmation_yes_2.response; console.log("Multiple rides Message after") console.log(JSON.stringify(multipleRides)) fulfillmentMessages.push(multipleRides) fulfillmentMessages.push(noRides) console.log("Going to send these messages") console.log(JSON.stringify(fulfillmentMessages))

我希望这会有所帮助!