在尝试找到一种方法来运行存储在数组(如下面的数组)中的某些函数时,我产生了以下代码。
这可以正常工作,但是有时它似乎在上一个函数完成之前执行了一个函数。
如何防止在以前的代码完成之前在下面的代码中执行功能?
具有多个函数“调用”和参数的数组的示例
["A3",[6]],["B1",["TEST",4,13]],["A10",[2]],["A7",[1,5]]
从上面的数组执行每个函数调用的for循环
function routineConverter(v){
var routines = JSON.parse('[' + v + ']');
for ( var i=0; i < routines.length ; i++ ){
switch (routines[i][0]) {
case 'A1':
routines[i] = A1( routines[i][1] );
break;
case 'A2':
routines[i] = A2( routines[i][1] );
break;
case 'A3':
routines[i] = A3( routines[i][1] );
break;
case 'A4':
routines[i] = A4( routines[i][1] );
break;
case 'A5':
routines[i] = A5( routines[i][1] );
break;
case 'A6':
routines[i] = A6( routines[i][1] );
break;
case 'A7':
routines[i] = A7( routines[i][1] );
break;
case 'A8':
routines[i] = A8( routines[i][1] );
break;
case 'A9':
routines[i] = A9( routines[i][1] );
break;
case 'A10':
routines[i] = A10( routines[i][1] );
break;
case 'B1':
routines[i] = B1( routines[i][1] );
break;
case 'B2':
routines[i] = B2( routines[i][1] );
break;
case 'E':
routines[i] = conditionalAction( routines[i][1] );
break;
case 'X1':
//console.log(routines[i][1]);
routines[i] = REMOVE(routines[i][1] ); //B1( routines[i][1] );
break;
}
}
var a = [routines];
}
函数示例:
function A1(p) {
$('#tbl tr td:nth-child(' + parseInt(p) + ')').after('<td></td>');
}
最佳答案
我留下评论,询问您的问题是什么,因为我希望有更好的解决方案。不管我有什么答案。您需要将要调用的函数放入对象中,以便该解决方案起作用。您还将需要ES6支持或使代码美化。
const calls = [["A3",[6]],["B1",["TEST",4,13]],["A10",[2]],["A7",[1,5]]];
const functions = {
A3: function (...args) {
console.log('A3', args);
},
B1: function (...args) {
console.log('B1', args);
},
A10: function (...args) {
console.log('A10', args);
},
A7: function (...args) {
console.log('A7', args);
}
};
const functionCaller = fns =>
fns.map(([fn, ...args]) => functions[fn](...args));
console.log(functionCaller(calls));
在这里,
functionCaller
函数接收调用数组,例如在顶部定义的那些,并映射它们,并返回其结果数组。映射通过分解数组来工作,初始元素始终是函数的名称,其余元素是参数,使用destructuring syntax和spread operator将其分隔成各自的数组
然后,我们将此函数名称作为对象的键,调用带有参数请求的特定方法。
当您运行代码段时,您将看到正确的函数名称以及所传递的参数,但是由于未定义的函数均未返回任何内容,因此将返回未填充的数组。如果他们这样做,我们将看到该数组已被填充。
关于javascript - 如何防止函数数组中的函数在上一个函数完成之前执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49439168/