简体   繁体   English

替换数组中的元素

[英]Replace elements in an array

What is a clean way to replace elements in an array in ES2019?在 ES2019 中替换数组中元素的干净方法是什么?

This is my code, but it iterates the array multiple times:这是我的代码,但它多次迭代数组:

function findReplace(item, target, replacement){
  return item === target ? replacement : item
}

const a = [1,2,3,4,5,5,4,3,2,1]
console.log(a.map(item => findReplace(item, 1, 10))
             .map(item => findReplace(item, 2, 20)))
//[10,20,3,4,5,5,4,3,20,10]

Create a map for the translation:为翻译创建一个 map:

 const a = [1,2,3,4,5,5,4,3,2,1] const map = new Map([[1, 10], [2, 20]]); console.log(a.map(item => map.get(item)??item)) //[10,20,3,4,5,5,4,3,20,10]

If you want to replace values with null or even undefined , then the ??如果你想用null甚至undefined替换值,那么?? operator is not the right tool.运算符不是正确的工具。 In that case:在这种情况下:

 const a = [1,2,3,4,5,5,4,3,2,1] const map = new Map([[1, null], [2, undefined], [3, 33]]); console.log(a.map(item => map.has(item)? map.get(item): item))

Another way is to use object called mapping .另一种方法是使用object称为mapping

 const a = [1,2,3,4,5,5,4,3,2,1] const mapping = {1: 10, 2: 20}; const result = a.map(v => mapping[v] || v); console.log(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM