简体   繁体   English

如何调用我从 JavaScript 中的数组中提取的函数?

[英]How do I call the function I pull out from an array in JavaScript?

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.链接的代码显示了一个包含 3 个不同函数的数组。 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. cut out 函数在控制台日志中显示良好,但我不知道如何调用该函数并执行它。 Anyone able to help me figuring out the correct way?任何人都可以帮助我找出正确的方法? I figured I'd use the new_numb like this (it does not work):我想我会像这样使用 new_numb (它不起作用):

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>

The array prototype function you're using returns an array with 1 index.您使用的数组原型函数返回一个索引为 1 的数组。 So you need to access it with [0] , then you can use apply() to call it.所以你需要用[0]访问它,然后你可以使用apply()来调用它。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM