如何以不可变方式连接数组JS [英] How to concat arrays immutable way JS

查看:67
本文介绍了如何以不可变方式连接数组JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何联系不可变的数组.假设我从数组list = [4,1]开始,然后从动作响应中接收数组,例如items = [5,2,6].我如何让数组表示结果为[4,1,5,2,6]并且该操作是不可变的.

I wonder how to contact array that is immutable. Lets imagine I start with array list = [4,1], and then I receive array from action response like so items = [5,2,6]. How do I concant arrays that the result is [4,1,5,2,6] and that operation is not mutable.

奖金:如何覆盖具有相同ID(不可变方式)的项目?让我们想象一下这是存储区books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]中的数组.其他需要覆盖书籍的数组(从API上次同步)otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}].所以结果应该是[{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]

Bonus: How do I overwrite items with same id (immutable way)? Lets imagine this our array in store books=[{'id':1, 'title': 'Cool story'}, {'id':2, 'title': 'Bad story'}]. Other array that needs to overwrite books (last sync from API) otherArray = [{'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]. So result should be [{'id':2, 'title': 'Bad story'}], {'id':3, 'title': 'Super story'}, {'id':1, 'title': 'Very cool story'}]

推荐答案

JavaScript没有不可变的类型.

Javascript does not have immutable types.

听起来您实际上是在要求串联数组而不对现有实例进行变异.

It sounds like you're actually asking to concatenate arrays without mutating the existing instances.

文档中明确指出

As stated clearly in the documentation, the concat() method does that.

这篇关于如何以不可变方式连接数组JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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