简体   繁体   English

更改数组的最佳方法是什么?

[英]What would be the best way to change the array?

var pred = ['z','b','d','e','z','f','b','d']
                    
var conditions = [
    {new:"a", old:"z", func:"replace"}, //replace z with a
    {new:"c", old:"b", func:'add_and_replace'} // after b add c
]

I want to make changes to arr pred based on conditions我想根据条件对 arr pred进行更改

The result I'm looking for is pred = ['a','b','c','d','e' 'a','f','b','c','d']我正在寻找的结果是pred = ['a','b','c','d','e' 'a','f','b','c','d']

I'm trying to do it in this way but the output is incorrect :我正在尝试以这种方式执行此操作,但输出不正确

    var conditions = [
        {new:"a", old:"z", func:"replace"}, //replace z with a
        {new:"c", old:"b", func:'add_and_replace'} // after b add c
    ]
    var pred = ['z','b','d','e','z','f','b','d']
    let new_pred = []
    pred.forEach((pre,i)=>{
        conditions.forEach((con,j)=>{
         
          if(con.func == 'replace' && pre.includes(con.old)){
            new_pred.push(con.new)
          }
          if(con.func == 'add_and_replace' && pre.includes(con.old)){
           new_pred.push(pred[i]);
           new_pred.push(con.new)
         }
        })
        new_pred.push(pred[i])
    })

    pred = new_pred;
    console.log(pred)

How could I do it?我怎么能做到?

You could use the map and flatMap functions.您可以使用mapflatMap函数。

var conditions = [
    {new:"a", old:"z", func:"replace"}, //replace z with a
    {new:"c", old:"b", func:'add_and_replace'} // after b add c
]
var pred = ['z','b','d','e','z','f','b','d']

for (const condition of conditions) {
    switch (condition.func){
        case "replace":
            pred = pred.map(element => (element === condition.old) ? condition.new : element)
            break
        case "add_and_replace":
            pred = pred.flatMap(element => (element === condition.old) ? [element, condition.new] : element)
            break
    }
}

console.log(pred) // ["a", "b", "c", "d", "e", "a", "f", "b", "c", "d"]

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

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