I
I
Ivan S. Glushko2015-07-23 11:07:59
JavaScript
Ivan S. Glushko, 2015-07-23 11:07:59

What is the best way to traverse an array without going beyond its limits?

I'm asking for help in finding the best option for this situation.
There is a certain section of "spherical code in a vacuum":

var Arr = [][];
Arr.length = 100;

for(var i=0; i<100; i++) {
    for(var j=0; j<100; j++) {
        if(Arr[i + 10][j + 10] === 1) {
            // что-то произойдёт
        }
    }
}

Given a two-dimensional array of 100 x 100, when trying to substitute a condition without checking the length, which clearly exceeds the array limit, for example: Arr[i+10][j+10] - we get the corresponding error “cannot read property of undefined”. Maybe there is some other way to avoid piling up checks before the necessary condition?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vitaly Inchin ☢, 2015-07-23
@In4in

Why "heaps"? You just need to check if there is:
In general, you can set this 100 (it doesn’t come from nowhere?) via:
var s = Math.min(100, Arr.length);

P
Pavel Shvedov, 2015-07-23
@mmmaaak

Or add functionality using the forEach method . There are indexes and everything else. Well, if you access an array element, no one will check for its existence for you.

D
Dmitry Kovalsky, 2015-07-23
@dmitryKovalskiy

the array must have a length property. And if you don’t need indexes i, j to death, then try using foreach loops

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question