0

I have this javascript array of jquery commands:

var a = ["$('div').hide();","$('span').show();","$('p').fadeIn(100);"];

I want to execute, let's say the first command in the array, but with no use of

eval(a[0]);

Is there a better possible way to do so?

Thanks.

4
  • 5
    Why have it in a string to start? Commented Sep 11, 2014 at 13:02
  • does new Function(a[0])() works for you!!! - (it is the same as using eval :() Commented Sep 11, 2014 at 13:02
  • 1
    @ArunPJohny — That is, effectively, eval by another name. Commented Sep 11, 2014 at 13:03
  • @Quentin that is why the !!! Commented Sep 11, 2014 at 13:03

3 Answers 3

3

Given your precondition: no.

The better solution would be to change the array so it contained functions instead of strings.

var a = [
    function () {
        $('div').hide();
    },
    function () {
        $('span').show();
    },
    function () {
        $('p').fadeIn(100);
    }
];

a[0]();
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use an object with functions in it

var a = {
    hideDiv: function () {
        $('div').hide();
    },
    showSpan: function () {
        $('span').show();
    },
    fadeinP: function () {
        $('p').fadeIn(100);
    }
}

Use it like this

a.hideDiv();
a.showSpan();
a.fadeinP();

DEMO

Comments

1

Not an especially better way to do so, but a different way:

// create a new script element
var elem = document.createElement("script");
elem.type = "text/javascript";
elem.innerHTML = a[0];

// add it to the document body so it gets executed
document.getElementsByTagName("body")[0].appendChild(elem);

However, if you can choose to have a different data structure to start with and have functions instead of their source code, it becomes much easier and cleaner:

var a = [
    function() { $('div').hide(); },
    function() { $('span').show(); }
    function() { $('p').fadeIn(100); }];
// invokation is clean
a[0]();

2 Comments

Is the first option really better than using eval()?, is'nt it the same after all?
That's exactly why I said it's different but not better, yes it's basically an eval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.