0

So, I think my question should be fairly straightforward, I am just looking for a little clarification on why I'm getting these seemingly odd results when I try to use the Array.indexOf method with null. Here's my code:

var myArray:Array = new Array(20);
trace(myarray.indexOf(null)); //output: -1
trace(myarray[0] == null); //output true

So, it looks like the elements of an array are defaulted to null when a length constructor parameter is initialized, but why does indexOf(null) not return 0?

2
  • I could be wrong but I think null is a tricky thing to work with, especially with such functions. I would try swapping the lines (i.e. tracing the condition before tracing the function) and seeing if it makes a difference. Commented Feb 10, 2013 at 7:36
  • @puggsoy, the output is the same regardless of the order the statements come in (I would hope that it would be... I would be disturbed if the == operator modified my array to make indexOf work somehow :P ) Commented Feb 10, 2013 at 8:06

2 Answers 2

3

elements of an array are defaulted to null

Nope. It's a popular belief in JS & AS3. A property, when it has no definition, is undefined.

Besides, anyone implementing the indexOf function, would obviously check if the value to be searched is null before actually starting to search.

Also I think you are looking for this :

var myArray:Array = new Array(20);
trace(myArray.indexOf(undefined)); //output: 0
trace(myArray[0] == null); //output true
Sign up to request clarification or add additional context in comments.

Comments

2

If only a single numeric parameter is passed to the Array constructor, it is assumed to be length and it is converted to an integer by using the Integer() function. http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000737.html

var myArray:Array = new Array(20);
trace(myArray.length); //output: 20

As for the difference between null and undefined you can check this http://www.bobbyberberyan.com/2011/01/as3-undefined-vs-null/

1 Comment

ooh, +1 for the null vs undefined link, I didn't realize as3 was so javascripty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.