我有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]);
}
}
}
似乎您需要类似两个数组的交集的东西。这是两个数组之间的共同点。您可以使用filter
和indexOf
来完成。
var master = ['hhhh', 'yyyy'];
var array = ['adf','hhhh','jjj'];
const common = array.filter(item => master.indexOf(item) > -1);
console.log(common);
如果需要交叉点,可以使用此方法
let intersection = master .filter(x => array .includes(x));
这完全取决于您要实现的目标
您可以使用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);
}
})
}