我有一个训练任务来检查该数组是否与另一个数组匹配。找到的匹配项必须替换为任何值。
在一种情况下,我做到了,但是使用 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; }
关于javascript - 如果数组中的项目与另一个数组中的项目一致,则替换它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58455310/