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>
return this.splice(randomnr, 1)[0];then call as you weremy_array[new_numb]();(or with.apply()or.call()as noted in the answer).