Article From:https://segmentfault.com/q/1010000012137414
Question:
var a = [
  {
    name: 'is_empty',
    items: ['1', '2', '3', '4', '5']
  },
  {
    name: 'is_true',
    items: ['6', '7', '8', '9', '10']
  }
]
var b = []

for (var i = 0; i < a.length; i++) {
  b[i] = a[i]
}

// Note a[0] = [], B at this time is B [], ['1','2','3','4','5']}/ / without note, B is {[1, 2, 3, 4, 5]}, {[6, 7, 8, 9, 10.]]]/ / a[0] = []/ / console.log (b) / / {['6','7','8','9','10']}, {['6','7','8','9','8'// a[0].items = []/ / / / console.log (b) / / ([] [], [6, 7, 8, 9, 10]}

Reseta[0] = []The reference to the array was cut off, but only reset.a[0].items = []When the quotation was not cut off, why?

Answer 0:

Let’s assume that there is an array [[a].

aIt is its pointer, pointing to the address of this array.

Then you create a variable B, put the element address in that array in B, because the element in that array isobject So the operation of b[i] = a[i] is only a[i] assigning an address to b[i].They are all a pointer

The following branch:

a[0] = []The situation is that a[0] is originally a pointer to one of the elements, then it is replaced by a pointer to [empty] array. Then an attribute item is added to the object (that is, empty array) of this pointer, which is a pointer to an empty array. B still points to [}, [}], there is no effect.

a[0] = []Annotated case: the next statement a[0].item = []. Before this statement executes, a[0], like b[0], is a pointer to an element. After executing this statement, that is, the item attribute of the object that a[0] points to.A pointer that covers an empty array. But the memory address that b[0] points to is still unchanged, or the same as a[0]. So b[0].item also points to the memory, so b[0].item = a[0].item = [].
(The operation of the attribute operation performs the operation on the memory address block of the object. )

The point to note is that the assignment of reference type is to transfer the address of the object to the variable and make the variable its pointer. So a[0] = b[0] is all pointing to an element of [n. Maybe you had a very good intention before var B = [] opened up a memory.. But what is stored in this new memory is the pointer to [[x], P]. That is, there are three address blocks involved in the article. One is to store the address of the a array, one is to store the address of the B array, the other is the address of [[]

Reference Keywords: Call by sharing

With examples, I hope to understand:

Welcome to correct and make progress together. The beginning of contact may describe the nonstandard.

Answer 1:

The two is not the same thing, a [0] refers to the first array element, and a [0] refers to the object attribute of the first array element, items, so the results you assign are certainly different.

Link of this Article: JS array reference

Leave a Reply

Your email address will not be published. Required fields are marked *