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
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) {
// ...
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With