Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array type being picked up as array value

I have some simple Javascript looping through an array of items (Tridion User Groups) to check if the user is a member of a specific group.

I can easily code around the issue shown below ( see && extensionGroup !== 'true') but I want to understand why the isArray = true is counted as a value in the array - any ideas?

The screenshot below demonstrates that the value extensionGroups has been set thus

var extensionGroups = ["NotEvenARealGroup", "Author", "ExampleGroupAfterOneUserIsActuallyIn"]; 

but returns the isArray value as a 4th value?

updated to show images a little clearer

Firebug - objects

Firebug - code

like image 250
Dylan .. Mark Saunders Avatar asked Feb 20 '23 09:02

Dylan .. Mark Saunders


2 Answers

You're using for in to iterate an array; don't do that. Use for (or forEach):

for(var i = 0; i < extensionGroups.length; i++) {
    var extensionGroup = extensionGroups[i];
    // ...
}

The reason this fails is because for in is used to iterate over an object's properties in JavaScript. Iterating over an array in this way means you get anything else assigned to it, such as this property or length.

And if you're able to use Array#forEach, it's probably most appropriate here:

extensionGroups.forEach(function(extensionGroup) {
    // ...
});
like image 193
Ry- Avatar answered Feb 27 '23 07:02

Ry-


For..in, technically speaking, doesn't iterate through values. It iterates through property names. In an array, the values ARE properties, under the hood. So when you iterate over them with for..in you get funky stuff like that happening.

Which highlights my next point: don't use for..in. Don't use it for arrays -- don't use it for anything, really. Ok -- maybe that's going a bit too far. How about this: if you feel the need to use for..in, think hard to see if it's justifiable before you do it.

like image 21
Phillip Schmidt Avatar answered Feb 27 '23 09:02

Phillip Schmidt