javascript - 如果数组中的项目与另一个数组中的项目重合,则替换它们
问题描述
我有一个培训任务来检查阵列是否与另一个阵列匹配。找到的匹配项必须替换为任何值。
在一种情况下,我做到了,但使用for...of
出现问题 - 我不明白为什么。
//source array
let arr = ['one', 'two', 'three', 'four', 'five', 'six'];
//array to compare
let arrForChange = ['one', 'four', 'six'];
从源数组更改一项很容易
let changedArr = arr.map(el => { if( el === 'four'){
return el = 4;
} else {
return el = el} }
);
// console.log(changedArr); // one,two,three,4,five,six
列表上的替换更有趣一些。我在这里使用.includes()
//This variant work
let cahngedArrFromList = arr.map(el => {
if(arrForChange.includes(el)){
return 'A';
} else {
return el;
}
});
// console.log(cahngedArrFromList); // A,two,three,A,five,A
寻找不同的选择更有趣。在这里我使用for...of
并且出现问题,结果不是我所期望的 - 只替换了第一个值。
//This variant do not work =(
let cahngedArrFromListTwo = arr.map(el => {
for (const item of arrForChange){
if (item === el){
return 'A';
} else {
return el;
}
}
});
// console.log(cahngedArrFromListTwo); // A,two,three,four,five,six
如果您删除条件else
,那么一切似乎都有效......但没有
let cahngedArrFromListThree = arr.map(el => {
for (const item of arrForChange){
if (item === el){
return 'A';
} /* else {
return el;
} */
}
});
// console.log(cahngedArrFromListTree); // A,,,A,,A
你能解释一下for...of
行为吗?还是我使用不当?
解决方案
最简单的方法是将索引查找与替换映射结合起来。
如果数组中的当前项在过滤器列表中,则在替换映射中查找其值作为键并返回其值。如果映射中不存在该键,则返回原始值。
const replacements = {
'one' : 1,
'two' : 2,
'three' : 3,
'four' : 4,
'five' : 5,
'six' : 6
};
let filter = [ 'one', 'four', 'six' ],
input = [ 'one', 'two', 'three', 'four', 'five', 'six' ];
console.log(replaceArrayItem(input, filter, replacements));
function replaceArrayItem(arr, filterArr, replMap) {
return arr.map(item => filterArr.indexOf(item) > -1 ? replMap[item] || item : item);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
推荐阅读
- jquery - 带有 Twitter API 的 jquery $.post 有效,但回调函数不返回数据
- python - 单击像素后如何打破循环并重新截取屏幕截图?
- byte-buddy - ByteBuddy 在方法参数上“传播”对象数组的能力有哪些限制?
- python - 人脸识别无法安装
- xamarin - Xamarin.Android (BiometricPrompt):缺少 setAllowedAuthenticators() 方法
- sql - Oracle分析SQL中的KEEP和OVER有什么区别
- javascript - TypeScript 中的承诺
- arrays - 为什么我使用 firstIndex(其中:
- javascript - 在 php 或 javascript 中单击按钮后禁用该按钮
- c++ - 如何干净地编写我的虚函数