0

Below is a piece of working code. The "= true" part is confusing to me. This is what I think is happening.

1- create empty array.
2- take the selected list items (targets) and loop.
3- if the class attributes for the target list item is not in the array then enter if block.
4- add the class attributes for the target list item and add them to the array.

My understanding is that javascript uses "push" and jquery uses "add" to insert items into an array. The code below does not use push or add.

var foo = [];
$($targets).each(function(i) {
    if (!foo[$(this).attr('class')]) {
        foo[$(this).attr('class')] = true;
    }
});
user584583
  • 1,242
  • 4
  • 18
  • 35
  • what do you get when you console.log( foo ); ...? – Sudhir Bastakoti Oct 03 '13 at 02:58
  • I understand now. The foo['something'] = true; syntax confused me. I now see it is a key value pair as explained here http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object-literal – user584583 Oct 03 '13 at 11:57

2 Answers2

2

The code is flawed, you'd use an object instead of an array if you want to use strings as keys:

var foo = {};

Then it checks if the key is falsy in the object, although you may want to check for strict existence with the in operator:

$targets.each(function() {
  var klass = this.className; // cache, no need for jQuery
  // if `foo` doesn't have the key `klass` then add it
  if (! (klass in foo)) foo[klass] = true;
});
elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

Unless the class names are numbers like "1" or "2", you can't access items inside the array that way. That said, arrays are built from objects. So for example you can do things like this:

var foo = ['a', 'b', 'c'];
foo.bar = 'hello';

foo;
//=> ['a', 'b', 'c']

foo[0];
//=> 'a';

foo['bar'];
//=> 'hello';

So what's happening is that your script is not adding those items into the actual array. Instead, it's assigning them to the array as if it was a regular JavaScript object.

rescuecreative
  • 3,607
  • 3
  • 18
  • 28
  • haha similar question and you as well are creating properties on it... – PSL Oct 03 '13 at 03:29
  • haha you're right. It should be noted that this is not usually the proper way to use an array. If you're not going to populate it with ordered items, it is better to use an object. – rescuecreative Oct 03 '13 at 13:59