I have the following array:
var x = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
I have to check that the position exists inside the array. For example x[4][1]
it should be false, and it should x[2][2]
be true.
I did the following function:
function posicionValida(i,j){
for (var i = 0; i < x.length; i++) {if (x[i]==undefined){
return false}
for (var j = 0; j < x.length; j++){
if (x[j]==undefined){
return false
} else {return true} }}}
But it's not working. How could I do it?
You can do it very simply by comparing the sizes of each dimension, if vertically i exceeds the length of x you send false, if you don't check j in the array x[i] , if it exceeds you send false, if not then the position exists:
Update: you can reduce the function to a single line and avoid negative numbers like this:
Previous answer:
can be used also
.hasOwnProperty
Arrays are also objects, and the indices would be some of the properties of that object, since
hasOwnProperty
it does not check the inherited properties, only the indices and would remain.length
.Before answering the question, keep in mind that
Having this clear, you only have to validate if
x[i]
and itx[i][j]
exists in this order, as you know the logic gates always validate the second one if the first one is fulfilled; and something extra! you must use the double negative !! to convert the value to booleanComplementing the question, JavaScript can do more operation by taking the values to primitives, so I send you to read
This function should work with pos1 and pos2 of type int:
It will return true if the indices passed to the function are positive and less than the respective lengths (taken in sizes, not indices, hence > instead of >=) of each position, putting pos1 as the length of [1, 2, 3], for example, and pos2 as the length of all the internal arrays that compose them.
The other codes jump with an error in case of entering negatives, instead this one in your case will return false.