Question

I am writing a greasemonkey script and using an external script that creates a preferences window. The preferences window is initialized with the following code:

USP.init({
        theName: 'show_advd',
        theDefault: true
    }, {
        theName: 'show_ahd',
        theDefault: true
    }, {
        theName: 'show_at',
        theDefault: true
    }, {
        theName: 'show_bithd',
        theDefault: true
    }, {
        theName: 'show_bmtv',
        theDefault: true
    });

The code is actually about 50 of those blocks instead of just 5, and it is constantly being updated. What I want to do is have an external file of the names that would be read in and made into an array. For test purposes I'm just using a test array.

var test = ['test0','test1','test2'];

Now I was planning on using a for loop to make the block so I would have just one instead of 50, but I can't figure out how to not break the formatting that's necessary.

It would look something like this:

USP.init(
for(int i=0;i<test.length;i++)
{
    {
        theName: test[i],
        theDefault: true
    }
});

But obviously that doesn't work. Thoughts on a workaround?

Was it helpful?

Solution

You can't include a for-loop like that because it is a statement and does not evaluate to an expression. You can only have expressions as arguments to a function, and the {...} terms here are object literals, which are just expressions that evaluate to an object.

What you need to do is create an array with your for-loop and pass that in to your function using Function.apply.

Here is an example:

var args = [];

for (var i = 0; i < test.length; i++) {
  args.push({
    theName    : test[i],
    theDefault : true
  });
}

USP.init.apply(USP, args)

The apply method takes two arguments. The first one is the value of this inside the function; it has to be the object you want to call the function on. The second argument is an array, it will be passed into the function as its arguments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top