1

I am trying to make a news system. I have a table where each element is a function producing text.

I have a loop that checks whether news+number is a function or undefined. If it is a function, then I push news+number to the array [number].

I am using eval, because i don't know any other way to push the function name and the number to the array.

CODE:

var tablicaNewsow = [news1,news2]

function addNews ()
{
  var counterArray = 0;
  var fName = " ";
  fName = "news1";
  while (eval('typeof' + " " + fName) == "function")
  {
    //---------------sprawdzenie czy news istnieje----------
    fName = "news" + (counterArray+1);
    if (eval('typeof' + " " + fName) == "function")
    {
      //------------jest news
      tablicaNewsow.push(eval(fName+"()"));
      }
    else
    {
      //-----------nie ma newsa
      }
    counterArray++;
  }
}

NOTE:This is a code segment from my system, which pushes functions in the array.

Sorry for my bad English.

2
  • Do what you want in other ways, if you can't skip the eval thing, you should probably think again why do you even need it! Commented Oct 16, 2012 at 16:08
  • Please don't eval! You can use an object and set a key using "array-like" notation: obj[key] Commented Oct 16, 2012 at 16:09

3 Answers 3

3

I think you're looking for window["news"+number] (or similar). Any global variable can be accessed in this way.

Otherwise you could just use an array instead of indexing multiple variable names.

Sign up to request clarification or add additional context in comments.

Comments

0

You can refer to a function name in the current scope using this:

if (typeof(this[fName]) == 'function') {
  this[fName]();
}

Or, if you're inside an object, but you know the functions live in the global scope, you can use window:

if (typeof(window[fName]) == 'function') {
  window[fName]();
}

Of course, if the the above snippet runs in the global/window scope -- or even in a function that lives in the global/window scope, this == window, and either option will work.

Comments

0

this is a code example that expects the functions to be global:

function addNews ()
{
    var counterArray = 0;
    var f = window["news1"];
    while (typeof f == "function")
    {
        //---------------sprawdzenie czy news istnieje----------
        f = window["news" + (counterArray+1)];
        if (typeof f == "function")
        {
            //------------jest news
            tablicaNewsow.push(f);
        }
        counterArray++;
    }
}

Comments

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.