2017-02-20 275 views
0

我試圖在這個對象中創建一個包含這個對象的變量的數組,但是我得到一個錯誤。 我使用這個錯誤嗎? THX的幫助在包含對象值的對象中創建一個數組

var data = { 
    p: [{content: "p", 
      text: "this is random text" }, 
      {content: "p", 
      text: "this is a second random text" 
     }], 
    img: [{content: "image", 
      src: "data/img/1_1.png", 
      alt: "This a an image"}, 
      {content: "image", 
      src: "data/img/1_2.png", 
      alt: "This is the second image"}], 
    title: {content: "title", 
      text: "Ceci est un titre"}, 
    //This doesn't work 
    all: [this.title, this.p[0], this.img[0], this.p[1], this.img[1]] 
} 
//But this works 
console.log(data.title); 
console.log(data.p); 
console.log(data.img); 
+2

您不能引用「正在建設中」對象的其他部分。 – Pointy

+0

你的代碼中'this'的上下文是什麼?注意這一點。 – tfidelis

+1

爲什麼在您可以輕鬆構建「全部」陣列時存儲冗餘信息? – Damon

回答

0

this關鍵字,直到它被建造不指向當前的對象。

我猜this指的是下一個最高範圍,或Window對象在你的情況。

在瀏覽器控制檯簡單的測試:

var a = {"test": this}; 
console.log(a["test"]); //Window 

你會更好做的蒼蠅查詢時,你需要的數據彙總這種方式,或者找到更好的方法來填充該屬性。

相關問題