【问题标题】:Javascript check array for data derived from other arraysJavascript 检查数组以获取从其他数组派生的数据
【发布时间】: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() 将在添加/删除任何 usertool 时运行。创建任务后,页面上的其他功能将被公开,并且数据将与任务对象一起存储。例如,一旦创建了任务,用户就可以在 UI 上添加 taskDuration。然后将该值作为属性存储在task 上。如果我每次都覆盖它,我想我会丢失那些数据吗?如果它仅在添加/删除用户/工具时运行,它不应该影响已经为其创建组合的任何内容,从而保持新数据完好无损。

标签: javascript arrays


【解决方案1】:

您可以使用some 处理这种事情。 这是一个例子:

var exists = tasks.some(task => task.TaskUser == user && task.TaskTool == tool);

【讨论】:

    【解决方案2】:

    您可以为此创建一个嵌套循环。

    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.
         */
    
        for (var i = 0; i < users.length; i++) {
            for (var u = 0; u < tools.length; u++) {
                if (!taskExists(users[i], tools[u]))
                    createTask(users[i], tools[u])
            }
        }
    }
    
    // Check if a task with the specified user&tool exists
    function taskExists(user, tool) {
        for (var i = 0; i < tasks.length; i++) {
            if (tasks[i].TaskUser == user && tasks[i].TaskTool == tool)
                return true
        }
        return false
    }
    
    // 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();
    

    【讨论】:

    • 我运行了代码,它工作正常。有人愿意解释它有什么问题吗?
    猜你喜欢
    • 1970-01-01
    • 2013-08-27
    • 2023-03-26
    • 2015-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-19
    相关资源
    最近更新 更多