1

I'm doing this project trying to reproduce Schelling's Segregation model. I have a function(below) that is testing to see if the four immediate adjacent cells of the array are either the same or different or empty compared to the current cell being tested.

There are four possible spots to be tested for every cell in the array. But on corners and side spots, obviously you cant test spaces that are out of bounds. So in the function, if it finds one of the out of bounds spaces it decrements the number total around the cell. However, it keeps crashing telling me that I have an Uncaught Reference Error: Cannot read property '0' of undefined. I can't tell why its crashing.

The final lines of this code take the number of goods(similar cells) and the total number of cells around it (empty cells do not count) and gets a percentage similar.

Any help would be appreciated into telling me why it might be crashing and giving me an error? Thanks!

model.Test = function( i, j )
{
var numberToTest= 4;
var goods= 0;

if ((i - 1) >= 0) 
{
    if (model.BoardArray[i-1][j] != "E")
    {
        if (model.BoardArray[i][j] == model.BoardArray[i-1][j])
        {
            goods++;
        }
    }
    else
    {
        numberToTest--;
    }
}
else
{
    numberToTest--;
}


if((i + 1) < $("#BoardSizeValue").val()) 
{
    if (model.BoardArray[i+1][j] != "E")
    {   
        if (model.BoardArray[i][j] == model.BoardArray[i+1][j])
        {
            goods++;
        }
    }
    else
    {
        numberToTest--;
    }
}
else
{
    numberToTest--;
}


if ((j - 1) >= 0) 
{
    if (model.BoardArray[i][j-1] != "E")
    {
        if (model.BoardArray[i][j] == model.BoardArray[i][j-1])
        {
        goods++;
        }
    }
    else
    {
        numberToTest--;
    }
}
else
{
    numberToTest--;
}


if ((j + 1) < $("#BoardSizeValue").val()) 
{
    if (model.BoardArray[i][j+1] != "E")
    {   
        if (model.BoardArray[i][j] == model.BoardArray[i][j+1])
        {
            goods++;
        }
    }
    else
    {
        numberToTest--;
    }
}
else
{
    numberToTest--;
}


var similar = $("#SimilarSlider").val()/100;
if (numberToTest == 0)
{
    return false;
}
else
{
    var needed = goods/numberToTest;

    if (needed >= similar)
    {
        return false;
    }
    else
    {
        return true;
    }
}
}
4

1 回答 1

0

通过查看您的代码,您只会得到一个Reference Error: Cannot read property '0' of undefined.ifi超出了数组的范围。

我认为问题可能出在这部分代码中:

if ((i - 1) >= 0) {
    if (model.BoardArray[i-1][j] != "E") {
        if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {

如果i = $("#BoardSizeValue").val()$("#BoardSizeValue").val()是数组大小的从一开始的索引,那么[i-1]可以,但不是[i]. 因此,请尝试将您的代码调整为:

if ((i - 1) >= 0 && i < $("#BoardSizeValue").val()) {
    if (model.BoardArray[i-1][j] != "E") {
        if (model.BoardArray[i][j] == model.BoardArray[i-1][j]) {

这也适用于j比较。

于 2013-02-13T04:52:56.463 回答