[Solved] Creating a JavaScript global array with static elements?


The problem isn’t that removeFunction doesn’t have access to bigArray. The problem is in your onclick attribute, and the id you’re putting on the link:

$('#div').append("<a href="#" id='bigArray[i]' onclick='removeFunction(bigArray[i])'>Element bigArray[i]</a><br />");

In the onclick, you’re referring to i, but A) I’m guessing i isn’t a global, and B) Even if it is, it will not have the value of i that you used to render that row. The code will look for the value of a global i variable as of when the link is clicked.

Separately, you’re creating multiple elements with the same id value, which is bigArray[i] (not bigArray[0], bigArray[1], etc.)

You could use the value instead, like this:

$('#div').append("<a href="#" id='bigArray[" + i + "]' onclick='removeFunction(" + i + ")'>Element bigArray[i]</a><br />");

The changes there are:

  • For the id, I changed it to: "...id='bigArray[" + i + "]'", which will output id='bigArray[0]', then id='bigArray[1]', etc., instead of repeatedly outputting id='bigArray[i]' (literally.

  • I just pass the index into removeFunction, again by putting the value there, not a reference to the variable i: "... onclick='removeFunction(" + i + ")' ..."

Then your removeFunction would be:

function removeFunction(i) {    // <== i, not id
    bigArray.splice(i, 1);      // <== real code, not pseudocode
    renderArray(bigArray);
}

I would not recommend doing it that way, but it’s the minimal fix.

There’s no need to pass bigArray to anything. It’s a global.


FWIW, I would recommend refactoring so you don’t have to re-render the whole thing every time.

4

solved Creating a JavaScript global array with static elements?