-1

how can i get this to work. there is always an error that it would not be defined. I've tried everything possible, but I can't get it to work

var delete_id1=[];
var delete_id2=[];
var delete_id3=[];


function push_array(clicked_element){

var the_array = "delete_id";

var the_id = clicked_element.id;

var finish_array = the_array+the_id;

finish_array.push("my_value");

}
<div onclick="push_array(this)" id="1">test1</div>

<div onclick="push_array(this)" id="2">test2</div>

<div onclick="push_array(this)" id="3">test3</div>

1 Answers1

-1

You can try this! This way you don't have to define the arrays.

function push_array(clicked_element) {
  var the_id = clicked_element.id;
  this["delete_id" + the_id] = [];
  this["delete_id" + the_id].push("my_value");

  console.log(this["delete_id" + the_id]);

}
<div onclick="push_array(this)" id="1">test1</div>

<div onclick="push_array(this)" id="2">test2</div>

<div onclick="push_array(this)" id="3">test3</div>
Tushar Wasson
  • 494
  • 5
  • 10
  • It's probably better to use `window` instead of `this` here, because `this` will be `undefined` in [strict mode](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode). (That being said, it is probably preferable to avoid polluting the global scope entirely.) – Ivar Jun 10 '21 at 08:57