Page 1 of 1

Array bug?

PostPosted: Fri Dec 10, 2010 11:16 am
by Marco R.
Hi all,

If I fill an array in this way:
Code: Select all
   for(var i=1;i<=7;i++)
      _myArray[i] = i;


And I check the ".length",I obtain 8 but the elements are 7!

if,instead,I create the array with the code:

Code: Select all
var _myArray = new Array(1,2,3,4,5,6,7)


Then the ".length" returns the right number(7).

Maybe something wrong with the array index that start from 1 and end with 7? Or I'm forgotten something?
Here a sample:
test_array_length.servoy
(3.48 KiB) Downloaded 245 times

Re: Array bug?

PostPosted: Fri Dec 10, 2010 11:26 am
by birgit
You are right. The problem is the index. JavaScript Arrays always start at index 0.
E.g.:
Code: Select all
var myArray = [1,2,3,4];  // myArray.length is 4, indexes range from 0 to 3.
myArray[8] = 8;          // myArray.length is now 9, myArray[4]..myArray[7] are undefined


Regards

Re: Array bug?

PostPosted: Fri Dec 10, 2010 11:57 am
by Marco R.
Thanks for your answer Birgit! :)

So because this is a JavaScript's behavior ,we have to take it as it is,right?

I'm using other count logic (a simple "for in"), I'm asking it just for knowledge

Re: Array bug?

PostPosted: Fri Dec 10, 2010 12:12 pm
by birgit
Array behaviour is different in almost every language. An interesting link showing this is:
http://en.wikipedia.org/wiki/Comparison_of_programming_languages_(array)

Regards