【发布时间】:2018-05-12 02:44:06
【问题描述】:
我有一小段代码要弄清楚。我有三个数组,一个用于users,另一个用于tools。
最后一个数组包含具有属性的对象,这些属性是每个用户和工具的组合。
示例:
var users = ['bob123', 'tim890'],
tools = ['admin', 'videos'],
tasks = [];
在上面的代码中,总共会有四个任务。 bob123/admin, bob123/videos, tim890/admin, tim890/videos.
我试图弄清楚如何签入对象数组 (tasks) 以查看是否存在用户/工具组合。如果没有,它会通过 create 函数运行它。
伪代码:
var users = ['bob123', 'tim890'],
tools = ['admin', 'videos'],
tasks = [];
// Check to see if tasks have been created for each tool/user combo
function checkTasks() {
/*
Loop over all the tasks.
If a task doesnt exist for a specific
tool/user combo, create it.
*/
// Pseudo Code
Loop Begin
if bob123 admin does not exist in tasks {
createTask('bob123', 'admin');
}
Loop End
}
// Create a new task if one doesn't exist
function createTask(user, tool) {
// Create a new task
tasks.push({
TaskUser: user,
TaskTool: tool
});
}
// Run our app
checkTasks();
检查存在于第三个数组的对象中的两个数组之间的数据组合的最佳方法是什么?
【问题讨论】:
-
为什么要检查?只需使用前两个数组的 cartesian product 覆盖整个数组即可。
-
checkTasks()将在添加/删除任何user或tool时运行。创建任务后,页面上的其他功能将被公开,并且数据将与任务对象一起存储。例如,一旦创建了任务,用户就可以在 UI 上添加 taskDuration。然后将该值作为属性存储在task上。如果我每次都覆盖它,我想我会丢失那些数据吗?如果它仅在添加/删除用户/工具时运行,它不应该影响已经为其创建组合的任何内容,从而保持新数据完好无损。
标签: javascript arrays