my previous question about this dealt with global vars
but unfortunatley the window of opportunitys doesn't work with this next example because it alerts 4 times instead of only 1

test("a","b","c");
function test(var0,var1,var2,var3) {
    for(var i=0; i<4; i++) {
        if(window["var"+i]===undefined) {alert("test");}
    }
}

this may not be very clear so I will try again
this time I want it to alert all three vars

test("a","b","c");
function test(var0,var1,var2) {
    for(var i=0; i<3; i++) {
        alert(window["var"+i]);
    }
}

how can I achieve the identical results as with the window["str"+var] from within a function?

Dani AI

Generated

Short answer: you can't turn a string into the name of a local variable the way you can with globals (window["..."]). Local parameter names are lexical identifiers, not properties on the global object. As hinted, treat the incoming values as a collection rather than trying to reconstruct local names.

A clean modern approach is to use rest parameters and work with an array of values:

function test(...values) {
  for (let i = 0; i < values.length; i++) {
    alert(values[i]);
  }
}

If you specifically need string-keyed lookup (e.g. you want to query "var0", "var1" by name), build or receive an object that maps those names to values:

function test(a, b, c) {
  const byName = { var0: a, var1: b, var2: c };
  alert(byName['var1']); // dynamic lookup works on the object
}

Or simply pass an array or object in the first place:

test(['a','b','c']);          // treat as ordered list
test({var0:'a',var1:'b'});    // treat as named map

Notes and cautions:

  • window["var"+i] only finds globals; local params won't be there.
  • You can convert the old-style arguments to a real array with Array.from(arguments) or the spread operator, but prefer rest parameters in new code.
  • Avoid using eval to resolve local names dynamically — it's slow and unsafe.
  • Make loops use the actual length (values.length or Object.keys(map).length) to avoid off‑by‑one alerts like the four-alert symptom you saw.

These patterns keep code clear, safe, and easy to maintain compared with trying to construct local variable names at runtime.

All of the values passed to a function are stored in "arguments".

test("a","b","c");
function test(var0,var1,var2) {
    for(var i=0; i<3; i++) {
        alert(arguments[i]);
    }
}
commented: thanks :) +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.