这个问题已经被问了很多遍了,但是我做不到我想要的,所以我寻求您的帮助。

我有2个数组checkMyDataSourceslesInfosMachines

我需要运行checkMyDataSources来检查lesInfosMachines中是否没有任何项目。
checkMyDataSources的内容可以是["datasource_A","datasource_B","datasource_D","datasource_C"]之类,并且名称与lesInfosMachines中包含诸如["A","B","C","D"]之类的每个项目的名称相关联。

问题是我无法遍历所有checkMyDataSources,我的意思是当单元格A和Amachine不同时,它会调用createDataSource,尽管Amachine可能在单元格D中。

var lesInfosMachines = InfosMachines.find({});
    if(checkMyDataSources.length < 1){
      console.log("there is not datasource, we will create them all");
      callInitDS();
    }else{
      console.log("there is datasource, we will check them");
      lesInfosMachines.forEach(Meteor.bindEnvironment(function(machineInfo) {
        console.log("test machine " + machineInfo.nameMachine)
        for (var i = 0; i < checkMyDataSources.length; i++) {
          console.log("test on " + checkMyDataSources[i].name.split("_")[1]);

          if(checkMyDataSources[i].name.split("_")[1] === machineInfo.nameMachine){
            console.log("Datasource:  " + machineInfo.nameMachine + " already exist." );
          }else{
            if(machineInfo.ipAddr != null){
              console.log("going to create " + machineInfo.nameMachine);
              createDataSource(machineInfo.nameMachine, machineInfo.ipAddr);
            }else{
              console.log("going to create " + machineInfo.nameMachine +
                          " with a fake @ip because it was null
                            ONLY FOR TESTING WE NEED TO REMOVE THIS"
                         );
              createDataSource(machineInfo.nameMachine, "myFakeIP");
            }
          };
        }
      }));
      console.log("test finished")
    }


我希望我的问题是可以理解的,并感谢您的帮助

[编辑]这是我的输出:
javascript - 即使未排序,如何在JavaScript中比较两个数组?-LMLPHP

[EDIT2]为简化起见,我想在checkMyDataSources的A,B,C,D上测试aMachine,如果其中一个单元格中没有aMachine(但最后),则调用createDataSource()

最佳答案

const datasources = ["datasource_A", "datasource_B", "datasource_D", "datasource_C"];
const lesInfosMachines = ["A", "D", "C"];
const prefixLength = "datasource_".length



如果要获取不在datasources上的lesInfosMachines

datasources.filter((d) => lesInfosMachines.every((l) => l !== d.slice(prefixLength)))
["datasource_B"]

如果要获取datasources上的lesInfosMachines

datasources.filter((d) => lesInfosMachines.some((l) => l === d.slice(prefixLength)))
["datasource_A", "datasource_D", "datasource_C"]

如果要让它返回true(如果datasources中有一些lesInfosMachines,则返回false,否则):

let otherLesInfosMachines = ["X", "Y", "Z"]

datasources.some((d) => otherLesInfosMachines.some((l) => l === d.slice(prefixLength)))
false

datasources.some((d) => lesInfosMachines.some((l) => l === d.slice(prefixLength)))
true



通过组合诸如filtereverysome之类的功能,您可以非常习惯地实现许多算法,而不必依赖于难以理解甚至语义上毫无意义的for循环和索引。

10-06 15:27