【发布时间】:2019-06-22 03:58:56
【问题描述】:
我有一个充满函数调用(即func(param);)的数组,如下所示:
var array = [
func(param),
func(param),
func(param)
];
稍后,我想一次调用所有这些函数调用。我该怎么做?
我知道您可以使用 for 循环或 forEach 对数组中的每个项目运行一个函数,如下所示:
for (var i = 0; i < 10; i++) {
// do stuff
}
或者
arrayName.forEach(function(e) {
// do stuff
});
但我不确定如何编写代码以便它执行调用?
我已经尝试了以下操作,但我收到错误“arrayName[i] 不是函数。”
for (i = 0; i < arrayName.length; i++) {
arrayName[i]();
}
编辑:三种解决方案
1:最好,使用 while 循环
这是基本代码:
var soundsWaitingForNextBar = [];
while (soundsWaitingForNextBar.length > 0) {
soundsWaitingForNextBar[0](); // call first item in array
soundsWaitingForNextBar.shift(); // remove first item in array
}
这是一个更深入的版本,其中项目每秒被推送到数组,但数组仅每 10 秒清空一次:
var soundsWaitingForNextBar = [];
function foo() {
console.log('')
} // just making sure foo is a function
// pusing some functions into the array
soundsWaitingForNextBar.push(() => foo());
soundsWaitingForNextBar.push(() => foo());
setInterval(function() { // pushing items to array periodically to make sure the while loop is only emptying when it is called by setInterval and not every time an item is added to the array
soundsWaitingForNextBar.push(() => foo());
}, 2000);
setInterval(function() {
// this while loop does the magic: it calls and removes each item in the array
while (soundsWaitingForNextBar.length > 0) {
soundsWaitingForNextBar[0](); // call first item in array
soundsWaitingForNextBar.shift(); // remove first item in array
}
}, 10000);
setInterval(function() { // just checking to see how/when items are added to the array and emptied
console.log('array.length: ' + soundsWaitingForNextBar.length);
}, 1000);
2:使用array[0](); 调用每个数组项/函数。
const func = console.log;
const param = 'foo';
const array = [
() => func(param),
() => func(param),
() => func(param)
];
console.log(array.length); // just noting the original array length
arrayLength = array.length;
for (let i = 0; i < arrayLength; i++) {
array[0]();
array.shift();
}
console.log(array.length); // just making sure the array is empty
3:使用array.forEach(fn => fn()); 调用每个数组项/函数。
const func = console.log;
const param = 'foo';
const array = [
() => func(param),
() => func(param),
() => func(param)
];
console.log(array.length); // just noting the original array length
array.forEach(fn => fn()); // calls each array item/function
arrayLength = array.length;
for (let i = 0; i < arrayLength; i++) {
array.shift();
}
console.log(array.length); // just making sure the array is empty
注意:在我最初使用.splice 从数组中删除项目的for 循环中,我使用了array.length。例如:for (let i = 0; i < array.length; i++)。这不起作用(我不确定为什么)所以我决定在 for 循环之前使用arrayLength = array.length; 确定数组长度。现在程序按预期运行。
【问题讨论】:
标签: javascript arrays function for-loop foreach