使用lodash替换数组 [英] Replace in array using lodash

查看:498
本文介绍了使用lodash替换数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以将数组中基元的所有外观替换为另一个基元。所以 ['a','b','a','c'] 将变为 ['x','b',' x','c'] x 替换 a 时。我知道这可以用map函数完成,但我想知道是否忽略了一种更简单的方法。

Is there an easy way to replace all appearances of an primitive in an array with another one. So that ['a', 'b', 'a', 'c'] would become ['x', 'b', 'x', 'c'] when replacing a with x. I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.

推荐答案

In您的示例所具有的字符串的特定情况,您可以使用以下内容进行本地操作:

In the specific case of strings your example has, you can do it natively with:

myArr.join(",").replace(/a/g,"x").split(",");

其中,是一些未出现在数组中的字符串。

Where "," is some string that doesn't appear in the array.

那说,我没有看到 _。map 的问题 - 这听起来像是更好的方法,因为这实际上是你在做什么。您将数组映射到自身并替换了值。

That said, I don't see the issue with a _.map - it sounds like the better approach since this is in fact what you're doing. You're mapping the array to itself with the value replaced.

_.map(myArr,function(el){
     return (el==='a') ? 'x' : el;
})

这篇关于使用lodash替换数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆