2011-12-28 3 views

答えて

100

それはあなたがプッシュしているものに依存します。オブジェクトと配列は元のオブジェクトへのポインタとしてプッシュされます。数字やブール値などの組み込みプリミティブ型はコピーとしてプッシュされます。したがって、オブジェクトはどのような方法でもコピーされないので、それらのための深いまたは浅いコピーはありません。ここで

はそれを示し、作業の抜粋です:

var array = []; 
 
var x = 4; 
 
var y = {name: "test", type: "data", data: "2-27-2009"}; 
 

 
// primitive value pushes a copy of the value 4 
 
array.push(x);    // push value of 4 
 
x = 5;      // change x to 5 
 
console.log(array[0]);  // array still contains 4 because it's a copy 
 

 
// object reference pushes a reference 
 
array.push(y);    // put object y reference into the array 
 
y.name = "foo";    // change y.name property 
 
console.log(array[1].name); // logs changed value "foo" because it's a reference

30

jfriend00はここにマークを右ですが、一つの小さな明確化:あなたが何をあなたを変更することはできませんという意味ではありません変数が指し示しています。つまり、yは、配列に入れた変数を最初に参照していますが、次に変数yを取得し、配列内のオブジェクトから切断してを返します。参照)配列によってのみ参照されているオブジェクトを変更することなく、完全に別のものである。 `new`に "切断" オブジェクト参照を使用して約

http://jsfiddle.net/rufwork/5cNQr/6/

var array = []; 
var x = 4; 
var y = {name: "test", type: "data", data: "2-27-2009"}; 

// 1.) pushes a copy 
array.push(x); 
x = 5; 
document.write(array[0] + "<br>"); // alerts 4 because it's a copy 

// 2.) pushes a reference 
array.push(y); 
y.name = "foo"; 

// 3.) Disconnects y and points it at a new object 
y = {}; 
y.name = 'bar'; 
document.write(array[1].name + ' :: ' + y.name + "<br>"); 
// alerts "foo :: bar" because y was a reference, but then 
// the reference was moved to a new object while the 
// reference in the array stayed the same (referencing the 
// original object) 

// 4.) Uses y's original reference, stored in the array, 
// to access the old object. 
array[1].name = 'foobar'; 
document.write(array[1].name + "<br>"); 
// alerts "foobar" because you used the array to point to 
// the object that was initially in y. 
+0

興味深い点。 –

+1

Downvoteの説明は?あなたが私にそれが何であるかを知らせなければ、問題を解決するのは難しいです。 – ruffin

+0

なぜ私にpingしますか?私はずっと前にこれを打ち切り、あなたの答えが好きでした。ここで投票の画面は次のとおりです。http://i.imgur.com/AnDt98c.png –

関連する問題