Representing 2d space of indeterminate size with JS arrays - negative indexes?

后端 未结 1 1410
既然无缘
既然无缘 2021-01-20 22:51

I\'d like to represent 2d cartesian cordinates in a 2d JS array. The 2d space is of indeterminate size (can extend into -x and -y space too). This is fine for positive x a

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 23:18

    Are you sure you need negative indizes? Usually every coordinate system for computer graphics starts at (0/0) in the upper left screen corner. And they draw their axes somewhere else.

    So, the solution for a finite size is just transforming the coordinates. Also, you can use negative indizes on Arrays, but better call that "keys on array Objects". If you know their limitations, you can use them:

    • Array.length works only for positive indizes.
    • Therefore, you can't loop from 0 to a.length - you will have to find another solution. (and don't think of for-in).
    • So, you will need to determine a negative start for the loop - let it be a constant, or even another property of your array Object (without the auto-update feature!).

    But, you say your space is indeterminate. The problem is just that there is no inifinite data structure - in no programming language. Of course array indizes could get very big, but do you really need them? I'm very sure that a twodimensional array with a size of (2^32)^2 is nothing but a huge waste of memory space - or at least something that makes your application extremely slow.

    It might be better to think of a one-dimensional array with objects representing points in. You can easily loop over it, you can have any number for coordinate values and they don't need that much memory.

    0 讨论(0)
提交回复
热议问题