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?

4

2 回答 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
于 2013-02-10T08:41:59.697 回答
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/

于 2013-02-10T13:28:33.460 回答