Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Code errors in some cases
Message
From
24/03/2018 01:18:02
 
General information
Forum:
Javascript
Category:
Coding, syntax & commands
Miscellaneous
Thread ID:
01658966
Message ID:
01658973
Views:
32
>Hi everybody,
>
>I'm looking at the following code:
>
>
> var lastIndex = model.nodes.length - 1;
>                    var newNode = model.nodes[lastIndex];
>
>
>I can see that nodes is an object (in that particular case) and it doesn't have length property, so lastIndex evaluates to NaN and it errors from there.
>
>It only happens when I try to drop a new object on the other object (not into the root object).
>
>The question is - how to code the above defensively so it works when nodes is an array of objects and then it's a single object? Should I first check hasOwnProperty('length')?

To me naming of "model.nodes" implies array/collection. Before adding too much going against duck typing concept find out if the case of "nodes" being a single object is really intended or should be "nodes[0]" with nodes.length===1
Previous
Reply
Map
View

Click here to load this message in the networking platform