简体   繁体   English

对象解构分配的任何方面是否通过引用?

[英]Are any aspects of object destructuring assignments by reference?

I have a program that is incrementing requests on a session cookie and printing them out to the console. 我有一个程序,它会增加会话cookie上的请求并将它们打印到控制台。 Initially, I was trying to figure out how I could save this data. 最初,我试图找出如何保存这些数据。 After logging in a couple places, I realized that the data was being saved/changed despite me having a seperate variable to hold what I thought was a temporary version of the req member object. 登录几个地方后,我意识到数据正在保存/更改,尽管我有一个单独的变量来保存我认为是req成员对象的临时版本。

This is the code that made me realize that the actual object was being changes when I incremented the variable I assigned it to: 这个代码让我意识到当我将赋值给它的变量递增时,实际对象正在发生变化:

recordRequest(req) {
  const { ip } = req.info;
  const { requestsPerSecond } = req.session;
    if (req.originalUrl.split('/').filter(Boolean)[0] == 'www.example.com') {
      requestsPerSecond[ip] = requestsPerSecond[ip] + 1 || 1;
    }
  console.log(req.session.requestsPerSecond);
}

I can't seem to find in the docs here or on Mozilla whether or not this is intended behavior, whether or not this is a result of my use of const (where you can mutate member variables), or there is some kind of weird bug going on. 我似乎无法在这里或Mozilla的文档中找到这是否是预期的行为,无论这是否是我使用const的结果(你可以改变成员变量),或者有某种奇怪的虫子在继续。 I also had trouble reproducing this example on a smaller scale, but I verified that nothing going in or going out of the function is affecting this chunk of code. 我也很难在较小的范围内复制这个例子,但我确认进入或离开函数的任何东西都不会影响这一块代码。

It's not breaking my code or anything (it's actually making my life easier) but I want to understand why this is happening! 它并没有破坏我的代码或任何东西(它实际上让我的生活更轻松)但我想知道为什么会这样!

I would default to object destructuring working essentially the same as normal assignments. 我将默认对象解构工作与正常分配基本相同。 Consider: 考虑:

const req = {session: {requestsPerSecond: {"0.0.0.0": "foo"}}};
const requestsPerSecond = req.session.requestsPerSecond;
// updates to `requestsPerSecond` will also update `req`.

I'm not sure you can use destructuring to break the assignment, so you will have to use normal tactics: 我不确定你是否可以使用解构来打破任务,所以你必须使用正常的策略:

const requestsPerSecond = Object.assign({}, req.session.requestsPerSecond);

From MDN: 来自MDN:

The destructuring assignment syntax is a JavaScript expression that makes it possible to extract data from arrays or objects into distinct variables. 解构赋值语法是一种JavaScript表达式,可以将数组或对象中的数据提取到不同的变量中。

If this data happens to be an object reference, this object reference will be copied into the new variable , or in your case constant. 如果此数据恰好是对象引用,则此对象引用将被复制到新变量或您的case常量中。

Minimal example: 最小的例子:

 const orig = { foo: { bar: 1 } } const { foo } = orig; console.log(foo.bar); // 1 console.log(orig.foo.bar); // 1 foo.bar++; console.log(foo.bar); // 2 console.log(orig.foo.bar); // 2 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM