I have a question about copying array objects.

Asked 1 years ago, Updated 1 years ago, 92 views

This question is a hash code of the student's questions.

.

Hello, teacher

I have a question.

.

function copyArray(array) {
  for ( var copy=[], i=0, l=array.length; i<l; ++i ) {
    copy[i] = array[i];
  }
  return copy;
}

var a = copyArray([3,6,9]);
var yu = [3,6,9,12];
var a = copyArray(yu);

.

In , yu == a also yu === a appears, as yu a a. yu == a was expected to be true. So I took yu[1] == a[1] and it was true.

Why is yu == a also false?

reference javascript reference-variable copy fast-frontend

2022-09-22 18:34

2 Answers

Hello ^ - ^

I answer your question.

First, let's organize "references" through code.

.

// Define variables a,b,c
var a, b, c;

// Refers to the same object in a variable
a = b = c = [3, 8, 12];

// Validate that each variable references the same object 
console.log(a == b); // true
console.log(b === c); // true

// Transform objects with b variables
b.shift(); // [8, 12]

// Validate that each variable references the same object 
console.log(a == b); // true
console.log(b === c); // true

.

The object that each variable references is Verified that it is the same object.

Now let's look at the questions and find out why. ^ - ^

Let's look at the code first and talk about it.

.

// See array in a variable
var a = [ 10, false, [1] ];

// Copy the array object that the a variable references to and assign it to the b variable
var b = copyArray(a); // [ 10, false, [1] ]

// a, b variables look the same, but do not refer to the same object
// The reason is that when an object is copied, it is no longer the same object
console.log(a == b); // false
console.log(a === b); // false

.

This is the point. The reference is for the same object Many variables share, but copied objects are no longer Do not share objects. In other words, the copied object is It looks the same, but it's a completely different object.

So let's apply the code and look at the results.

.

var yu = [3,6,9,12];
var a = copyArray(yu); // [3,6,9,12]

console.log(yu == a); // false
console.log(yu === a); // false

.

As with the code results discussed above,

The object looks like the same object when copied.

It is not the same object.

.

Now you know why, right?

Why yu == a is false.

And the reason a[1] == yu[1] is the same is

Because raw values were copied to values during the array copy process,

It says the data value is the same. ^ ^ - ^


2022-09-22 18:34

Sir, I'm asking you one more time if I understand~

-- yu, a has the same value Because it is a copied object and has a different reference position, the results show that == and === are false

-- So in conclusion, when you use the ==, === operators on an object, Unlike the primitive type, Should I understand that the location where the object is stored (?) is also compared? ^

^


2022-09-22 18:34

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.