-1

I have an array that is connected to an input text box called myTextbox. Let's call the array myArray. The code looks something like this:

var myArray:Array = myTextbox.text.split("|");

Later on, I have to get the length of myArray. If myTextbox was empty, what would be the length of myArray?

I am tracing the length, but it says 1 for when it's empty, and 1 for when it has one element. I believe that's an error. Could somebody please answer my question?

Pow Mert
  • 59
  • 7
  • Check this out, it might help. https://stackoverflow.com/questions/2369967/how-can-i-check-whether-an-array-is-null-empty – Oleeze Dec 17 '17 at 03:29

1 Answers1

1

"If myTextbox was empty, what would be the length of myArray"?

Check the docs under String's split option:

"If the delimiter parameter is undefined...
The entire string is placed into the first element ([0]) of the returned array."

It's nice that the entire string is returned. Your confusion lies in dealing with the returning of an empty string. The array has a length of 1 because something was returned and put there, but if you check you think you find nothing since it's an empty string like ""...

Test 1: (string with content)

myTextbox.text = "hello world";

var myArray:Array = myTextbox.text.split("|");

trace("myArray length       : " + myArray.length);
trace("myArray [0]          : " + myArray[0] );
trace("myArray [0] as Int   : " + int(myArray[0]) );

Which gives "hello world" as first element (at [0]), since no "|" exists in string as a delimiter...

myArray len        : 1
myArray [0]        : hello world
myArray [0] as Int : 0

Test 2: (empty string)

myTextbox.text = "";

var myArray:Array = myTextbox.text.split("|");

trace("myArray length       : " + myArray.length);
trace("myArray [0]          : " + myArray[0] );
trace("myArray [0] as Int   : " + int(myArray[0]) );

Which gives empty "" as first element (at [0]), since no "|" exists in string as a delimiter, the entire empty (zero-length) string now sits at [0]...

myArray length      : 1
myArray [0]         : 
myArray [0] as Int  : 0
VC.One
  • 14,790
  • 4
  • 25
  • 57