1

I'm stuck with a problem, and I can't seem to figure out where to go. The code linked shows an array of 3 different functions. When the button is clicked it randomly splices one item out of the array after each click until the array is empty.

The cut out function shows fine in the console log, but I cannot figure out how to call the function and execute it. Anyone able to help me figuring out the correct way? I figured I'd use the new_numb like this (it does not work):

my_array[new_numb]();

Any help would be greatly appreciated!

Code for reference:

function first_function() {
  console.log("test1");
}

function second_function() {
  console.log("test2");
}

function third_function() {
  console.log("test3");
}

Array.prototype.randsplice = function () {
  var randomnr = Math.floor(Math.random() * this.length);
  return this.splice(randomnr, 1);//removed extra variable
};

var my_array = [
  first_function,
  second_function,
  third_function,
];

var button = document.getElementById("clicker");

button.onclick = function () {
  if (my_array.length > 0) {
    var new_numb = my_array.randsplice();
    console.log(new_numb);

  } else {
    console.log('array is empty');
  }
};
<button id="clicker">Click</button> 

1
  • 1
    To simplify later access you can just return the element out of the splice. return this.splice(randomnr, 1)[0]; then call as you were my_array[new_numb](); (or with .apply() or .call() as noted in the answer). Commented Jul 17, 2021 at 21:19

1 Answer 1

2

The array prototype function you're using returns an array with 1 index. So you need to access it with [0], then you can use apply() to call it.

new_numb[0].apply(null) 

function first_function() {
  console.log("test1");
}

function second_function() {
  console.log("test2");
}

function third_function() {
  console.log("test3");
}

Array.prototype.randsplice = function() {
  var randomnr = Math.floor(Math.random() * this.length);
  return this.splice(randomnr, 1); //removed extra variable
};

var my_array = [
  first_function,
  second_function,
  third_function,
];

var button = document.getElementById("clicker");

button.onclick = function() {
  if (my_array.length > 0) {
    var new_numb = my_array.randsplice();
    new_numb[0].apply(null)
  } else {
    console.log('array is empty');
  }
};
<button id="clicker">Click</button>

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

1 Comment

That is amazing, works like a charm! Been stuck forever on it, always silly when the answer isn't that far from what I've already tried. Again thanks for the reply!

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.