从数组调用函数

Calling a function from an array

本文关键字:函数 调用 数组      更新时间:2023-09-26

我正试图通过从命令行读取的数字调用函数。这是我的代码:

saveuser = function(user, callback) {
      //..
};
removeuser = function() {
      //..
};
finduser = function() {
      //..
};
updateuser = function() {
      //..
}
var options = {
    1: { 
        option: "Save a User",
        execute: "saveuser( newuser, finduser )"
    },
    2: { 
        option: "Remove a User",
        execute: "removeuser()"
    },
    3: { 
        option: "Find a User",
        execute: "finduser"
    },
    4: { 
        option: "Update a User",
        execute: "updateuser()"
    }
}
function read() {
    console.log("");
    console.log( " Enter your choice: ");
    stdin = process.stdin;
    stdin.setEncoding('utf8');
    stdin.on('data', choice);
};
function choice (data) {
    data = parseInt(data);
    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data]["execute"];
};
read();

现在什么也没发生。如果我把函数名不作为字符串放在数组中,它们会立即执行。我知道我可以用一个长if/elsif来处理这个问题,但是有一种方法可以用数组来做到这一点吗?

当您从函数名中删除引号时,它们立即执行的原因是您有包含()的括号。所以去掉引号和圆括号:

saveuser函数稍微复杂一些,因为需要传递参数。这可以通过使用.bind()来处理,或者通过创建一个匿名函数(假设您在某处声明了newuser)。

var options = {
    1: { 
        option: "Save a User",
        execute: saveuser.bind(null, newuser, finduser)
    },
    2: { 
        option: "Remove a User",
        execute: removeuser
    },
    3: { 
        option: "Find a User",
        execute: finduser
    },
    4: { 
        option: "Update a User",
        execute: updateuser
    }
}

你的最后一个问题是在choice()函数中,你没有包括括号来实际执行函数。

options[data]["execute"]();
//                      ^^------ required to execute it 

请查看更改

var saveuser = function() {
     console.log('saveuser');
};
var removeuser = function() {
      console.log('removeuser');
};
var finduser = function() {
      console.log('finduser');
};
var updateuser = function() {
      console.log('updateuser');
}
var options = {
    1: { 
        option: "Save a User",
        execute: function() {
            saveuser(newuser, finduser );
        }
    },
    2: { 
        option: "Remove a User",
        execute: function () {
            removeuser();
        }
    },
    3: { 
        option: "Find a User",
        execute: function() {
            finduser();
        }
    },
    4: { 
        option: "Update a User",
        execute: function() {
            updateuser();
        }
    }
}
function read() {
    console.log("");
    console.log( " Enter your choice: ");
    stdin = process.stdin;
    stdin.setEncoding('utf8');
    stdin.on('data', choice);
};
function choice (data) {
    data = parseInt(data);
    console.log("You entered: " + data);
    console.log("You choose to do: " + options[data]["option"]);
    options[data].execute();
};
read();

您可以使用:

eval(options[data]["execute"]);