0

I would like to know if it's possible to pass a method/property as a parameter in JavaScript.

An example of this would be something like this:

function uniq(list, property) {
        var flags = [], output = [], l = list.length, i;
        for (i = 0; i < l; i++) {
            if (flags[list[i].property]) continue;
            flags[list[i].property] = true;
            output.push(list[i].property);
        }
        return output;
    }

Is it possible to do such a thing? I'm in the process of trying to read through a single list of objects but have quite a few methods that will read through this list, just with very similar methods so I wish to eliminate a bit of redundancy.

I've tried passing the property name as a string but obviously that has thrown back an error.

Zev
  • 11
  • 2
  • 3
  • You mean to want to call a method or access a property using the string value of a variable? use the `[]` notation. `var x = 'prop'; y[x] = 10;` – ste2425 Feb 16 '16 at 12:22
  • 2
    where is `a` coming from? – Nina Scholz Feb 16 '16 at 12:26
  • Using a string was just a guess I took at trying to pass the property name which didn't work. I don't really mind what type it is, as long as I can pass it as a parameter and point it to the specific item in each object – Zev Feb 16 '16 at 12:27
  • @NinaScholz Sorry Nina, I edited to make it a bit more readable. First time poster on here... – Zev Feb 16 '16 at 12:30
  • this `list[i].property` should be this `list[i][property]`. now should work you function. – Nina Scholz Feb 16 '16 at 12:31
  • 1
    @NinaScholz Thank you, that worked. I've struggling to find an answer for this all day. – Zev Feb 16 '16 at 13:38

0 Answers0