将内部Javascript替换为循环而不使用循环映射,过滤器,缩小吗?

问题描述 投票:-1回答:2

我有2个循环,外部循环已经是现有代码的一部分...但是新的循环我不知道它是否更慢,更难看或什么..但是我想我只是想融入现代js中与地图/减少/过滤器等...

代替显示真实代码,此示例应该足以解释代码

var master = ['hhhh', 'yyyy']

var array = ['adf','hhhh','jjj']


for (index = 0; index < master.length; index++) { 
    //console.log(master[index]); 

    for (index2 = 0; index2 < array.length; index2++) { 

       //console.log(array[index2]); 

       if(master[index] === array[index2]){
          console.log(array[index2]);
       }
    } 

} 
javascript ecmascript-6 mapreduce
2个回答
0
投票

似乎您需要类似两个数组的交集的东西。这是两个数组之间的共同点。您可以使用filterindexOf来完成。

var master = ['hhhh', 'yyyy'];
var array = ['adf','hhhh','jjj'];

const common = array.filter(item => master.indexOf(item) > -1);

console.log(common);

0
投票

如果需要交叉点,可以使用此方法

let intersection = master .filter(x => array .includes(x));

0
投票

这完全取决于您要实现的目标


0
投票

您可以使用map方法来像这样遍历数组:

var master = ['hhhh', 'yyyy']
var array = ['adf','hhhh','jjj']
for (index = 0; index < master.length; index++) { 
    //console.log(master[index]); 
    array.map(function(element){
        if(master[index] == element){
            console.log(element);
        }
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.