2016-09-26 80 views
0

採取以下類爲例:Javascript方法不填充法(陣列)

function TestClass() { 

    // public property 
    this.testArray = []; 

    // public function 
    this.populateArray = function() { 
    for (var y = 1; y <= 9; y++) { 
     for (var x = 1; x <= 12; x++) { 
     this.testArray[x + '-' + y] = true; 
     } 
    } 
    }; 
} 

當我打電話populateArray方法,它運行正常,但它不會修改testArray屬性。

我試過拉出來的方法,並通過原型添加它,但那也行不通。

TestClass.prototype.populateArray = function() {}; 

正在調用該方法的代碼是在這裏:

var testClass = new TestClass(); 
testClass.populateArray(); 

爲什麼沒有方法填充的財產?

+7

你如何測試數組是否被填充?問題可能是您正在向數組添加任意屬性,而不是數組元素。看來你應該使用一個對象而不是一個數組。即'var foo = []; foo.bar = 42; foo.length;'會產生'0',因爲'foo.bar'不被認爲是一個數組元素。爲了避免這樣的混淆,可以使用一個對象(或者更好的方法:'Map')而不是一個數組。 –

+2

您正在使用_array_,但您正在設置_object properties_。 JavaScript中的數組只有數字索引。如果您想使用字符串鍵(例如,其他語言中稱爲哈希),則需要使用一個對象:{}'。你可以在一個數組上設置隨機屬性,但它是_bad practice_,因爲它們決不會形成或形成「官方」。 – vlaz

+0

在調用該方法後,你期望數組看起來像什麼? – trincot

回答

0

使用索引存儲數組元素。

var arr = []; 

arr[1 + '-' + 2] = 2; 

arr.length這裏將是零,因爲'1-2'不是數組index.Here它是一個存儲在陣列對象的屬性。

0

有幾個與你指定數組的方式問題,請留言給的解釋:

function TestClass() { 

    this.testArray = []; 


    this.populateArray = function() { 
    for (var y = 0; y < 9; y++) { 
     this.testArray.push([]); //Create 9 arrays 
     for (var x = 0; x < 12; x++) { 
     this.testArray[y].push([]); //Create 12 arrays for every 'y' array 
     this.testArray[y][x] = true; //You were using a string to access an array value. You can only do that with objects 
     } 
    } 
    }; 
} 
0

這裏是你想寫我猜:

function TestClass() { 

    // public property 
    this.testArray = {}; // <-- Object! 
    var self = this;  // Saving this (the context) of TestClass 

    // public function 
    this.populateArray = function() { 
    for (var y = 1; y <= 9; y++) { 
     for (var x = 1; x <= 12; x++) { 
     self.testArray[x + '-' + y] = true; // Using self 
     } 
    } 
    }; 
} 

而且here it is運行。