簡體   English   中英

不了解對象行為

[英]Object Behavior is not understood

我使用JavaScript已經有一段時間了,但是從未遇到過這個問題:

var objArr = [];
var obj = {
  id:null,
  name:''
}

//Type 1: Why This do not work
    //create an array of 5 object
    for(var i=0; i<3; i++){
        obj.id = i;
        console.log(obj);
       objArr.push(obj); //What is wrong here
        }

    console.log(JSON.stringify(objArr)); // Have 5 objects in the array, But if you see this object is display the last object 
//output : [{"id":2,"name":""},{"id":2,"name":""},{"id":2,"name":""}]


//Type 2: Why This Works and why the above object works
var objArr=[];
    //create an array of 5 object
    for(var i=0; i<3; i++){
        console.log(obj);
       objArr.push({"id":i, "name":''});
        }

    console.log(JSON.stringify(objArr)); 
//output : [{"id":0,"name":""},{"id":1,"name":""},{"id":2,"name":""}]

也許我想念這里的對象。 您能告訴我為什么會這樣嗎?

我有一個jsfiddle.net 小提琴

在第一個示例中,您有一個(只有一個)對象obj 您要創建一個由3個(而不是5個)對象組成的數組,但是數組中的每個位置都指向同一對象

設置obj.id ,您將為一個唯一對象更改它,該對象在數組的每個位置都被引用。

在第二個示例中,您每次都創建一個新對象:

{"id": i, "name":''}          // this creates a new object

這樣就行了。

嘗試使用如下形式:

var objArr=[];

for(var i=0; i<3; i++){
    var obj = {};
    obj['id'] = i;
    obj['name'] = null;
    console.log(obj);
   objArr.push(obj); 
    }

console.log(JSON.stringify(objArr));

您只需要在第一個for循環內創建一個新的obj。 您只是在for循環外編輯當前定義的obj。 因此,每個循環將一個obj的id設置為其i值,然后將其副本插入數組,因此在下一個循環中,對原始對象的每個引用都將更改。

在for循環中,我剛剛添加了'var',所以obj是一個新變量,而不是父作用域中的同一個變量:

var obj.id = i;

但是您可能想要重新格式化它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM