Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Code errors in some cases
Message
De
24/03/2018 01:18:02
 
 
Information générale
Forum:
Javascript
Catégorie:
Codage, syntaxe et commandes
Divers
Thread ID:
01658966
Message ID:
01658973
Vues:
33
>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
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform