简体   繁体   English

当分配给变量 object 时,变量的行为如何?

[英]How a variable behaves when an object assigned to it?

The application gets an object from the HTML form via the post method like this:应用程序通过 post 方法从 HTML 表单中获取 object,如下所示:

code:代码:

app.post("/foo", (req, res)=> {

  const data = req.body;
  const itemId = req.body.id;

  console.log(data);
  console.log(itemId);

});

console.log() results are: console.log()结果是:

{
  brand: 'foo',
  model: 'foo',
  amount: '10',
  id: '629f3149ffc8f9dcfa56e403'
}
629f3149ffc8f9dcfa56e403

On the console, the whole object and the item's value are shown perfectly.控制台上完美显示了整个object和物品的价值。

Now when I apply delete to remove the id property from const data before assigning req.body.id to itemId : (position1)现在,当我在将req.body.id分配给itemId之前应用deleteconst data中删除id属性时:(position1)

app.post("/foo", (req, res)=> {

  const data = req.body;
  // position 1
  delete data.id;
  
  const itemId = req.body.id;
  

  console.log(data);
  console.log(itemId);

})

I get undefined for itemId :我得到undefineditemId

{
  brand: 'foo',
  model: 'foo',
  amount: '10',
  
}
undefined

But if I use delete after assigning req.body.id to itemId : (position2)但是如果我在将req.body.id分配给itemId之后使用delete : (position2)

app.post("/foo", (req, res)=> {

  const data = req.body;
  
  const itemId = req.body.id;
  // position 2
  delete data.id;
  

  console.log(data);
  console.log(itemId);

})

I get the itemId in the console .我在console中获得了itemId

{
  brand: 'foo',
  model: 'foo',
  amount: '10',
}
629f3149ffc8f9dcfa56e403

The Question is why and/or how this happens?问题为什么和/或如何发生这种情况?

I embrace any edit on the Question's title/or body for better understanding for anybody.为了让任何人更好地理解,我接受对问题标题/或正文的任何编辑。 Thanks.谢谢。

Objects and values are treated differently in Javascript assignments.对象和值在 Javascript 赋值中被区别对待。

data and req.body are objects , and after the assignment datareq.body对象,赋值后

const data = req.body;

they are the same object. The object is not copied, but a new pointer to the same object is created.它们是相同的 object。object 没有被复制,而是创建了一个指向相同 object 的新指针。

Now现在

const itemId = req.body.id;
delete data.id;

first copies the value of id into a new variable and then deletes the original ( data.id is the same as req.body.id ).首先将id的值复制到一个新变量中,然后删除原始变量( data.idreq.body.id相同)。 The copy survives.副本幸存下来。

delete data.id;
const itemId = req.body.id;

first deletes the original id and then attempts to copy its value.首先删除原始id ,然后尝试复制其值。 But by then, it is gone.但到那时,它已经消失了。

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

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