2016-09-26 77 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运行。