未捕获的类型错误:无法设置未定义的属性'0'

时间:2022-08-24 13:55:15

i'm getting the error

我得到错误

Uncaught TypeError: Cannot set property '0' of undefined

未捕获的类型错误:无法设置未定义的属性'0'。

for some reason in this line

因为某些原因。

world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif";

Why is this happening?

为什么会这样?

thanks for any help

感谢任何帮助

var x_world_map_tiles = 100; 
var y_world_map_tiles = 100; 

var world_map_array = new Array(x_world_map_tiles);
for (i=0; i<=2; i++)//create a two dimensional array so can access the map through x and y coords map_array[0][1] etc.
{
world_map_array[i]=new Array(y_world_map_tiles);
}


for (i=0; i<=x_world_map_tiles; i++)//just a test
{
for (z=0; z<=y_world_map_tiles; z++)//just a test
{
world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif";
}
}

5 个解决方案

#1


26  

Arrays in JavaScript have quirks of their own that you may not be expecting if you come from other languages. Two important ones for your use case are:

JavaScript中的数组有其自身的特点,如果您来自其他语言,您可能不会期待。两个重要的用例是:

  1. You cannot directly declare multidimension arrays in JavaScript.
  2. 不能直接在JavaScript中声明多维数组。
  3. There's little efficiency benefit (and no added safety) when you set the size of the array at creation.
  4. 当您在创建时设置数组的大小时,几乎没有效率的好处(也没有额外的安全性)。

Unlike other languages, JavaScript won't allocate a block of memory for the full array. (It doesn't know what kind of objects you're going to be putting in each cell, and therefore how much total memory it will need.) Instead, all the size argument to Array() does for you is set the array's length property.

与其他语言不同,JavaScript不会为整个数组分配内存块。(它不知道你将在每个单元中放入什么类型的对象,因此它需要多少内存。)相反,对数组()的所有大小参数都是为您设置数组的长度属性。

For the general, 2d array case, I'd suggest:

对于一般的二维数组情况,我建议:

  1. Create the "top" array, e.g.:

    创建“顶部”数组,例如:

    var i       // the first-order index in a
      , j       // the second order index in a
      , a = []
    
  2. Initialize array elements as needed. This is called lazy initialization, and, in this case, it simply involves testing that a[i] exists before we try to assign something to a[i][j], e.g.:

    根据需要初始化数组元素。这就是所谓的延迟初始化,在这种情况下,它只是涉及到在我们试图将某个东西分配给一个[i][j]之前存在一个[i]的测试。

    if (!a[i]) a[i] = []
    

    In English the above statement reads: "If the i-th element of a is 'falsy', assign an empty array to the i-th element."

    在英语中,上面的语句是:“如果a的第i个元素是‘falsy’,那么将一个空数组赋给i-th元素。”

  3. Finally, assign the actual value to the multideminsional array:

    最后,将实际值分配给multideminsional数组:

    a[i][j] = 'whatever'
    

For your case, you know the values ahead of time, so you can initialize each element in advance. (If you're not overriding most of the elements, however, a lazy implementation may be better; see below.)

对于您的情况,您提前知道了值,因此可以提前初始化每个元素。(但是,如果您没有重写大多数元素,那么延迟实现可能更好;见下文)。

var x, x_length = 100
  , y, y_length = 100
  , map = []

// Don't be lazy
for (x = 0; x < x_length; x++) {
  map[x] = []
  for (y = 0; y < y_length; y++) {
    map[x][y] = 'grass.gif|ongrass.gif|collision.gif|above.gif'
  }
}

As some others have said, an array with 100 elements has indexes numbered from zero to ninety-nine, so a less-than comparison is most appropriate here.

正如其他一些人所说的,一个包含100个元素的数组的索引从0到99,所以这里最合适的是小于比较。


For reference, here's an implementation that uses lazy initialization. I've gone with a function interface instead of directly accessing the array; it's longer and more complex, but also more complete.

这里是一个使用延迟初始化的实现。我使用了一个函数接口而不是直接访问数组;它更长更复杂,但也更完整。

The initialization pattern I've used here is called an immediately invoked function expression. If you haven't seen it before, it's one of the more useful JavaScript patterns and well worth taking some time to understand.

我在这里使用的初始化模式称为立即调用的函数表达式。如果您以前没有见过它,它是更有用的JavaScript模式之一,值得花一些时间去理解。

var map = (function (x_length, y_length, v_default, undefined) {
  // Unless v_default is overwritten, use ...
  v_default = v_default || 'grass.gif|ongrass.gif|collision.gif|above.gif'

  // Private backing array; will contain only values for a[x][y] 
  // that were explicitly set.
  var a = []

  // Private helper function. 
  // - Returns `true` if `x` is between `0` and `x_length - 1`
  //   and `y` is between `0` and `y_length - 1`.
  // - Returns `false` otherwise.
  function valid (x, y) {
    return (x >= 0 
      &&    x <  x_length
      &&    y >= 0
      &&    y <  y_length)
  }

  // Private helper function.
  // - Returns `true` if a[x][y] has been set().
  // - Returns `false` otherwise.
  function exists (x, y) {
    return !!a[x] && !!a[x][y]
  }

  // Private getter
  // - Returns the value of a[x][y] if it has been set().
  // - Returns `undefined` if the point (x,y) is invalid.
  // - Returns `v_default` otherwise.
  function get (x, y) {
    if (!valid(x, y))      return undefined
    else if (exists(x, y)) return a[x][y]
    else                   return v_default
  }

  // Private setter
  // - Returns the value set on success.
  // - Returns `undefined` on failure
  function set (x, y, v) {
    if (valid(x, y)) {
      // We're being lazy
      if (!a[x]) a[x] = []
      a[x][y] = v
      return a[x][y]
    }
    return undefined
  }

  // Return an interface function. 
  // - Pass the function three arguments, (x, y, v), to set a[x][y] = v
  // - Pass the function two arguments, (x, y), to get a[x][y]
  return function (x, y, v) {
    if (arguments.length > 2) {
       return set(x, y, v)
    } else {
       return get(x, y)
    }
  }
})(100, 100)

When I ran the above in node, the following tests printed sensible values:

当我在节点上运行上面的代码时,下面的测试输出了合理的值:

// Invalid invocations
console.log('map()                : %s', map())
console.log('map(  0)             : %s', map(0))
console.log('map( -1,   0)        : %s', map(-1,0))
console.log('map(  0,  -1)        : %s', map(0, -1))
console.log('map( -1,  -1)        : %s', map(-1, -1))

// Valid invocations
console.log('map(  0,   0)        : %s', map(0, 0))
console.log('map( 99,  99)        : %s', map(99, 99))
console.log('map(  1,   1)        : %s', map(1,1))
console.log('map(  1,   1, "foo") : %s', map(1,1, 'foo'))
console.log('map(  1,   1)        : %s', map(1,1))

#2


2  

This

for (i=0; i<=2; i++)

must be:

必须:

for (i=0; i<=x_world_map_tiles ; i++)

#3


2  

var x_world_map_tiles = 100;
var y_world_map_tiles = 100;
var world_map_array = new Array(x_world_map_tiles);
for (i=0; i<=2; i++)//create a two dimensional array 
{
    world_map_array[i]=new Array(y_world_map_tiles);
}
for (i=0; i<x_world_map_tiles; i++)
{
    for (z=0; z<y_world_map_tiles; z++)
    {
        world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif";
    }
}

As your array has a length of 100, you must go from 0 to 99 (<100) and not to 100 (<=)

当数组长度为100时,必须从0到99(<100),而不是100 (<=)

#4


0  

You're feeding the world_map_array[i] expression a value for i that does not exist in world_map_array. So I guess x_world_map_titles is > 2.

您正在给world_map_array[i]表达式提供一个值,该值不存在于world_map_array中。我猜x_world_map_title是> 2。

I think you need to rewrite i<=2 to i<=x_world_map_titles

我认为您需要重写I <=2到I <=x_world_map_title。

Also you do not need to specify the size of the array. I would just use literals in this case:

另外,您不需要指定数组的大小。在这个例子中,我只使用文字:

var x_world_map_tiles = 100;  
var y_world_map_tiles = 100; 

var world_map_array = [];
for (i=0; i<=x_world_map_tiles; i++)
  //create a two dimensional array of 101x101 so can access the map through x and y coords map_array[0][1] etc. { 
  world_map_array[i]=[];
}

for (i=0; i<=x_world_map_tiles; i++)//just a test { 
  for (z=0; z<=y_world_map_tiles; z++)//just a test { 
    world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif"; 
  }
}

#5


-1  

Getting Uncaught TypeError while using 2-D array in javascript.

在javascript中使用2-D数组时,会出现未捕获的类型错误。

For two- dimension array, first declare parent array

对于二维数组,首先声明父数组。

var arryTwoDimension= [];

var arryTwoDimension =[];

Then depending on the situation, we can create child array by

根据情况,我们可以创建子数组。

arryTwoDimension[i]=[] i will be from 0,1,2......

arryTwoDimension[i]=[]我将从0,1,2……

This will solve the issue.

这将解决这个问题。

#1


26  

Arrays in JavaScript have quirks of their own that you may not be expecting if you come from other languages. Two important ones for your use case are:

JavaScript中的数组有其自身的特点,如果您来自其他语言,您可能不会期待。两个重要的用例是:

  1. You cannot directly declare multidimension arrays in JavaScript.
  2. 不能直接在JavaScript中声明多维数组。
  3. There's little efficiency benefit (and no added safety) when you set the size of the array at creation.
  4. 当您在创建时设置数组的大小时,几乎没有效率的好处(也没有额外的安全性)。

Unlike other languages, JavaScript won't allocate a block of memory for the full array. (It doesn't know what kind of objects you're going to be putting in each cell, and therefore how much total memory it will need.) Instead, all the size argument to Array() does for you is set the array's length property.

与其他语言不同,JavaScript不会为整个数组分配内存块。(它不知道你将在每个单元中放入什么类型的对象,因此它需要多少内存。)相反,对数组()的所有大小参数都是为您设置数组的长度属性。

For the general, 2d array case, I'd suggest:

对于一般的二维数组情况,我建议:

  1. Create the "top" array, e.g.:

    创建“顶部”数组,例如:

    var i       // the first-order index in a
      , j       // the second order index in a
      , a = []
    
  2. Initialize array elements as needed. This is called lazy initialization, and, in this case, it simply involves testing that a[i] exists before we try to assign something to a[i][j], e.g.:

    根据需要初始化数组元素。这就是所谓的延迟初始化,在这种情况下,它只是涉及到在我们试图将某个东西分配给一个[i][j]之前存在一个[i]的测试。

    if (!a[i]) a[i] = []
    

    In English the above statement reads: "If the i-th element of a is 'falsy', assign an empty array to the i-th element."

    在英语中,上面的语句是:“如果a的第i个元素是‘falsy’,那么将一个空数组赋给i-th元素。”

  3. Finally, assign the actual value to the multideminsional array:

    最后,将实际值分配给multideminsional数组:

    a[i][j] = 'whatever'
    

For your case, you know the values ahead of time, so you can initialize each element in advance. (If you're not overriding most of the elements, however, a lazy implementation may be better; see below.)

对于您的情况,您提前知道了值,因此可以提前初始化每个元素。(但是,如果您没有重写大多数元素,那么延迟实现可能更好;见下文)。

var x, x_length = 100
  , y, y_length = 100
  , map = []

// Don't be lazy
for (x = 0; x < x_length; x++) {
  map[x] = []
  for (y = 0; y < y_length; y++) {
    map[x][y] = 'grass.gif|ongrass.gif|collision.gif|above.gif'
  }
}

As some others have said, an array with 100 elements has indexes numbered from zero to ninety-nine, so a less-than comparison is most appropriate here.

正如其他一些人所说的,一个包含100个元素的数组的索引从0到99,所以这里最合适的是小于比较。


For reference, here's an implementation that uses lazy initialization. I've gone with a function interface instead of directly accessing the array; it's longer and more complex, but also more complete.

这里是一个使用延迟初始化的实现。我使用了一个函数接口而不是直接访问数组;它更长更复杂,但也更完整。

The initialization pattern I've used here is called an immediately invoked function expression. If you haven't seen it before, it's one of the more useful JavaScript patterns and well worth taking some time to understand.

我在这里使用的初始化模式称为立即调用的函数表达式。如果您以前没有见过它,它是更有用的JavaScript模式之一,值得花一些时间去理解。

var map = (function (x_length, y_length, v_default, undefined) {
  // Unless v_default is overwritten, use ...
  v_default = v_default || 'grass.gif|ongrass.gif|collision.gif|above.gif'

  // Private backing array; will contain only values for a[x][y] 
  // that were explicitly set.
  var a = []

  // Private helper function. 
  // - Returns `true` if `x` is between `0` and `x_length - 1`
  //   and `y` is between `0` and `y_length - 1`.
  // - Returns `false` otherwise.
  function valid (x, y) {
    return (x >= 0 
      &&    x <  x_length
      &&    y >= 0
      &&    y <  y_length)
  }

  // Private helper function.
  // - Returns `true` if a[x][y] has been set().
  // - Returns `false` otherwise.
  function exists (x, y) {
    return !!a[x] && !!a[x][y]
  }

  // Private getter
  // - Returns the value of a[x][y] if it has been set().
  // - Returns `undefined` if the point (x,y) is invalid.
  // - Returns `v_default` otherwise.
  function get (x, y) {
    if (!valid(x, y))      return undefined
    else if (exists(x, y)) return a[x][y]
    else                   return v_default
  }

  // Private setter
  // - Returns the value set on success.
  // - Returns `undefined` on failure
  function set (x, y, v) {
    if (valid(x, y)) {
      // We're being lazy
      if (!a[x]) a[x] = []
      a[x][y] = v
      return a[x][y]
    }
    return undefined
  }

  // Return an interface function. 
  // - Pass the function three arguments, (x, y, v), to set a[x][y] = v
  // - Pass the function two arguments, (x, y), to get a[x][y]
  return function (x, y, v) {
    if (arguments.length > 2) {
       return set(x, y, v)
    } else {
       return get(x, y)
    }
  }
})(100, 100)

When I ran the above in node, the following tests printed sensible values:

当我在节点上运行上面的代码时,下面的测试输出了合理的值:

// Invalid invocations
console.log('map()                : %s', map())
console.log('map(  0)             : %s', map(0))
console.log('map( -1,   0)        : %s', map(-1,0))
console.log('map(  0,  -1)        : %s', map(0, -1))
console.log('map( -1,  -1)        : %s', map(-1, -1))

// Valid invocations
console.log('map(  0,   0)        : %s', map(0, 0))
console.log('map( 99,  99)        : %s', map(99, 99))
console.log('map(  1,   1)        : %s', map(1,1))
console.log('map(  1,   1, "foo") : %s', map(1,1, 'foo'))
console.log('map(  1,   1)        : %s', map(1,1))

#2


2  

This

for (i=0; i<=2; i++)

must be:

必须:

for (i=0; i<=x_world_map_tiles ; i++)

#3


2  

var x_world_map_tiles = 100;
var y_world_map_tiles = 100;
var world_map_array = new Array(x_world_map_tiles);
for (i=0; i<=2; i++)//create a two dimensional array 
{
    world_map_array[i]=new Array(y_world_map_tiles);
}
for (i=0; i<x_world_map_tiles; i++)
{
    for (z=0; z<y_world_map_tiles; z++)
    {
        world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif";
    }
}

As your array has a length of 100, you must go from 0 to 99 (<100) and not to 100 (<=)

当数组长度为100时,必须从0到99(<100),而不是100 (<=)

#4


0  

You're feeding the world_map_array[i] expression a value for i that does not exist in world_map_array. So I guess x_world_map_titles is > 2.

您正在给world_map_array[i]表达式提供一个值,该值不存在于world_map_array中。我猜x_world_map_title是> 2。

I think you need to rewrite i<=2 to i<=x_world_map_titles

我认为您需要重写I <=2到I <=x_world_map_title。

Also you do not need to specify the size of the array. I would just use literals in this case:

另外,您不需要指定数组的大小。在这个例子中,我只使用文字:

var x_world_map_tiles = 100;  
var y_world_map_tiles = 100; 

var world_map_array = [];
for (i=0; i<=x_world_map_tiles; i++)
  //create a two dimensional array of 101x101 so can access the map through x and y coords map_array[0][1] etc. { 
  world_map_array[i]=[];
}

for (i=0; i<=x_world_map_tiles; i++)//just a test { 
  for (z=0; z<=y_world_map_tiles; z++)//just a test { 
    world_map_array[i][z]="grass.gif|ongrass.gif|collision.gif|above.gif"; 
  }
}

#5


-1  

Getting Uncaught TypeError while using 2-D array in javascript.

在javascript中使用2-D数组时,会出现未捕获的类型错误。

For two- dimension array, first declare parent array

对于二维数组,首先声明父数组。

var arryTwoDimension= [];

var arryTwoDimension =[];

Then depending on the situation, we can create child array by

根据情况,我们可以创建子数组。

arryTwoDimension[i]=[] i will be from 0,1,2......

arryTwoDimension[i]=[]我将从0,1,2……

This will solve the issue.

这将解决这个问题。