COMMUNITY

Interesting JavaScript target error when looping through array

I’ve stumbled upon an interesting behavior. And, for reference, I’m on the latest and greatest Haxe 4.1.4.

I have a nested JSON object, comprising of an array of “Children” objects, each of whom may contain other “Children” object arrays. So, like any ignorant Haxe developer, I try to loop like this:

var children = jsonObject.Hierarchy.Children;
//console.dir(children[0]);
for (i in 0...children.length)
{
	console.log("====== This child =========");
	console.dir(children[i]);
}

Which results in this error:

DataParser.hx:35: characters 17-25 : Array access is not allowed on {+ length : Int }
DataParser.hx:35: characters 17-25 : For function argument ‘obj’
Command failed: haxe build.hxml --connect 6060 -debug -D source-map-content
Command failed: npx task build:compile:debug

But… anybody dares to guess what happens if I uncomment the line that prints children[0]? :smiley:

And of course, it’s not related to printing the first element, but simply accessing it. This line has the same effect:

var firstChild = children[0];

jsonObject.Hierarchy.Children has unknown type, so it infers the type from how you use it. Here you access .length, so haxe assumes the type is { length: Int }, however this type inference doesn’t extend to array access. What you want to do is explicitly give the type for children here, for example:

var children: Array<SomeType> = jsonObject.Hierarchy.Children;

Replace SomeType with whatever the type of the children is, or Dynamic if you dont know

1 Like

Hehehe :slight_smile: I actually read an ancient post on SO that was hinting that I need Reflection to do it ( https://stackoverflow.com/questions/15530645/how-can-i-iterate-dynamic-object-in-haxe ) and I was like… “no way, this must be possible some other way”.

Thank you for the explanation :slight_smile:. Love our tight knit community :100:

On another note… man… Haxe’s error messages are so… last century. There’s not even any friggin’ “obj” in my code. That’s just stuff that I have to dig in through compiled code or who-knows-where. I compare this with some error messages I got from React this year. It’s like it knows exactly what I’m doing wrong, giving me education and links on the fly. sigh I guess that’s what the billions of sold advertisement FaceBook made can do to a framework. Gosh I can’t wait to be able to sink some millions into Haxe :smiley:

1 Like