简体   繁体   English

ES6 / ECMAScript6解构是否会创建新变量?

[英]Does ES6/ECMAScript6 destructuring create new variable?

As you know, we use destructuring to use the values in objects with ES6. 如您所知,我们使用解构来使用ES6对象中的值。 I wonder about its depth. 我想知道它的深度。

When I write the code below: 当我写下面的代码时:

let (or const) { firstVar, secondVar } = this.props

does it allocate new space in memory or does it use these values like pointers? 它是在内存中分配新空间还是像指针一样使用这些值?

In the past, when I wrote 在过去,我写的时候

let { options } = this.props
options.splice(0,20)

I noticed that the variable in props had changed although my compiler had errors like 'props are Readonly' on different cases. 我注意到,虽然我的编译器在不同的情况下有像'props is readonly'这样的错误,但是道具中的变量已经改变了。 How could it be possible? 怎么可能呢?

let and const declare new variables, yes. letconst声明新变量,是的。 They are independent from the object property after the assignment/initialisation. 它们在赋值/初始化后独立于对象属性。

when I wrote let { options } = this.props; options.splice(0,20) 当我写了let { options } = this.props; options.splice(0,20) let { options } = this.props; options.splice(0,20) I noticed that the variable in props had changed let { options } = this.props; options.splice(0,20)我注意到道具中的变量已经改变了

Yes, that's because your options are an array, and both the variable and the object property point to the very same mutable array instance. 是的,那是因为你的选项是一个数组,变量和object属性都指向同一个可变数组实例。 Assignment did not copy its contents . 作业没有复制其内容

There is a conflation here between destructuring and splice . 这里有一个解构拼接之间的混淆。

Destructuring will bind a variable to the value contained within the object it is destructuring from. 解构将变量绑定到它正在解构的对象中包含的值。

In your second example, options will be a key on the this.props object; 在第二个示例中, options将是this.props对象的一个​​键; when you print options out, then the original this.props.options object will be used. 当您打印出options时,将使用原始的this.props.options对象。

So it's a reference; 所以它是一个参考; in the way you phrased it, it's a variable that points to another variable. 就像你说的那样,它是一个指向另一个变量的变量。

However, you are also using splice which is a in-place/destructive operation that has side-effects. 但是,您也在使用splice ,这是一种具有副作用的就地/破坏性操作。

slice will return a new array, splice will modify the existing array. slice将返回一个新数组, splice将修改现有数组。

If you want to leave this.props.options alone, you will need to use slice : 如果你想单独留下this.props.options ,你需要使用slice

let { options } = this.props
options.slice(0, 20) // does not modify the existing array, returns a new array

options.splice(0,20) // modifies the existing array, returns the array of deleted items;

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

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