javascript - 如果数组中的项目与另一个数组中的项目一致,则替换它们

标签 javascript arrays loops for-loop replace

我有一个训练任务来检查该数组是否与另一个数组匹配。找到的匹配项必须替换为任何值。

在一种情况下,我做到了,但是使用 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/

相关文章:

c - C 中使用结构数组指针进行循环控制

PHP 如果第一个 MySQL 查询的结果为零,循环另一个查询直到找到结果

javascript - Javascript 原型(prototype)继承中数组和数字数据类型之间有区别吗?

javascript - 无法将 html 数组传递给 JS

c - 打印数组时出现随机字符

javascript - 如何在 Phaser 3 中将一组对象移动相同的距离?

python - 根据原始字典中的 N 个键创建 N 个新字典

javascript - 如何使用 .js 文件通过 document.write() 显示网页

javascript - 为什么用于 AES 加密的 Googles Javascript 代码在此代码中不起作用?

PHP - 类数组中带有括号的奇怪语法错误