You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constbooks=['Positioning by Trout','War by Green'];constnewBooks=[...books,'HWFIF by Carnegie'];// newBooks are now ['Positioning by Trout', 'War by Green', 'HWFIF // by Carnegie']
为一个数组创建视图
如果需要实现用户从购物车中删除物品,但是又不想破坏原来的购物车列表,可以使用filter方法。
constmyId=6;constuserIds=[1,5,7,3,6];constallButMe=userIds.filter(id=>id!==myId);// allButMe is [1, 5, 7, 3]
constbooks=[];constnewBook={title: 'Alice in wonderland',id: 1};constupdatedBooks=[...books,newBook];//updatedBooks的值为[{title: 'Alice in wonderland', id: 1}]
constparams={color: 'red',minPrice: 8000,maxPrice: 10000};constquery='?'+Object.keys(params).map(k=>encodeURIComponent(k)+'='+encodeURIComponent(params[k])).join('&');// encodeURIComponent将对特殊字符进行编码。// query is now "color=red&minPrice=8000&maxPrice=10000"
现如今JavaScript有许多问题,但是词法并不是其中之一。不管是三元运算符,还是map/reduce等ES6方法,亦或是扩展运算符(...)都是非常强大的工具。
除了能够保证可读性以及准确性,这些方法还有助于实现不可变性,因为这些方法会返回新的数据,而处理前的原始数据并不会被修改。这样的处理风格很适合redux以及Fractal。
话不多说,让我们开始吧。
一个简单的reduce实践
当你想要将多个数据放进一个实例中时,你可以使用一个reducer。
传给reduce的第一个参数函数还可以增加2个参数:
所以,一个reducer的完全体应该是下面这样的:
一个简单的map实践
map方法的作用在于处理流式数据,比如数组。我们可以把它想象成所有元素都要经过的一个转换器。
一个简单的find实践
find返回数组或类似结构中满足条件的第一个元素。
一个简单的filter实践
filter方法可以筛除数组和类似结构中不满足条件的元素,并返回满足条件的元素组成的数组。
向数组中新增元素
如果你要创建一个无限滚动的ui组件(比如本文后面提到的例子),可以使用扩展运算符这个非常有用的词法。
为一个数组创建视图
如果需要实现用户从购物车中删除物品,但是又不想破坏原来的购物车列表,可以使用filter方法。
向对象数组添加新元素
books这个变量我们没有给出定义,但是不要紧,我们使用了扩展运算符,它并不会因此失效。
为对象新增一组键值对
使用变量作为键名为对象添加键值对
修改数组中满足条件的元素对象
找出数组中满足条件的元素
删除目标对象的一组属性
感谢Kevin Bradley提供了一个更优雅的方法:
他还表示这个方法在对象属性更少时也能发挥作用。
将对象转化成请求串
你也许几乎遇不到这个需求,但是有时候在别的地方会给你一点启发。
获取数组中某一对象的下标
作者总结
有了这些强大的方法,我希望你的代码会变得越来越稳定和一丝不苟。当你的团队中有一个新的开发者加入时,可以向他推荐这篇文章,让他了解以前不知道的秘密。
The text was updated successfully, but these errors were encountered: