this is my attempt

var test=["a","b","c"];
var var0="a";
for(var i=0; i<1; i++) {
    test.splice(test.indexOf(test[window["var"+i.toString()]]),1);
}
alert(test);

it alerts "a,b" but I want it to alert "b,c"

ref:http://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript

Dani AI

Generated

Nice find, — the original expression was doing an extra array lookup which made the index calculation fail. ’s reply (compute index, check for -1, then splice) is a solid, defensive fix if you want to remove a single occurrence and keep mutating the original array.

A cleaner and more maintainable pattern is to collect the values you want to remove into one structure, then build the result from the original array instead of repeatedly calling indexOf inside a loop. This also avoids relying on dynamically named globals (the window['var'+i] approach only works for true globals and is hard to read).

const items = ['a','b','c'];
const removals = ['a'];               // populate this array from your vars
const removalSet = new Set(removals);
const result = items.filter(x => !removalSet.has(x));
// result -> ['b','c']

Notes and trade-offs:

  • filter + Set removes all matching entries and returns a new array (non‑mutating). Assign back to the original variable if you need to replace it.
  • If you must remove only the first occurrence per value, loop the removals and use indexOf + splice (like suggested), but be aware that repeated indexOf in a large loop is O(n^2).
  • If your values are not global, store them in an array or an object (namespace) you control instead of attempting dynamic scope lookups.
  • Use let/const in modern code for clarity and avoid brittle dynamic variable names — a single array or map is easier to maintain and faster for lookups when converted to a Set.

Recommended Answers

All 2 Replies

Member Avatar for Member #120589

So what are you trying to do? Remove an item from an array and display the resulting array as a string?

var test = ["a","b","c"];
var var0 = 'a';

var index = test.indexOf(var0);

if (index > -1) {
    test.splice(index, 1);
    alert(test.toString());
}else{
    alert(var0 + ' not in array');
}

Imagine there are more than one var but they are named like var0, var1, var2, [..]
and I want to iterate through them, i was just use a smalle scale simplified example
I was close but I found the bug in line 4, within indexOf
This is what I was looking for

var test=["a","b","c"];
var var0="a";
for(var i=0; i<1; i++) {
    test.splice(test.indexOf(window["var"+i.toString()]),1);
}
alert(test);

Thanks for your reply
my next question about this here

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.