在不使用循环的情况下替换内部 Javascript for 循环,而不是使用 map 、 filter 、 reduce ?
Replace inner Javascript for loop without using loop, instead maybe use map , filter, reduce?
我有 2 个循环,外层循环已经是现有代码的一部分了……但是我不知道新循环是否更慢、更丑陋还是什么……但我想我只是想成为使用 map/reduce/filter 等进入现代 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);
}
})
}
我有 2 个循环,外层循环已经是现有代码的一部分了……但是我不知道新循环是否更慢、更丑陋还是什么……但我想我只是想成为使用 map/reduce/filter 等进入现代 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);
}
})
}